Ernesto
Ernesto

Reputation: 53

how to validate an xml string in java?

I have seen some examples here, which show how to validate an xml File (It´s workking), but my question is: How can I modify this code to validate an String

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.util.List;
import java.io.*;
import java.util.LinkedList;
import java.net.URL;
import java.sql.Clob;
import java.sql.SQLException;
public class Validate {  

    public String validaXML(){

        try {
         Source xmlFile = new StreamSource(new File("C:\\Users\\Desktop\\info.xml"));
         URL schemaFile = new URL("https://www.w3.org/2001/XMLSchema.xsd");
         SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
         Schema schema = schemaFactory.newSchema(schemaFile);
         Validator validator = schema.newValidator();
         final List exceptions = new LinkedList();
         validator.setErrorHandler(new ErrorHandler()
          {
          @Override
          public void warning(SAXParseException exception) throws SAXException
          {
           exceptions.add(exception);
          }
          @Override
          public void fatalError(SAXParseException exception) throws SAXException
          {
           exceptions.add(exception);
          }
          @Override
          public void error(SAXParseException exception) throws SAXException
          {
           exceptions.add(exception);
          }
          });

         validator.validate(xmlFile);

          } catch (SAXException ex) {
              System.out.println( ex.getMessage());
              return ex.getMessage().toString();

          } catch (IOException e) {
          System.out.println( e.getMessage());
          return e.getMessage().toString();
         }
        return "Valid";
    }

    public static void main(String[] args) {
        String res;
       Validate val = new Validate();
       res=val.validaXML();
        System.out.println(res);
    }
}

I have tried with this:

 Source xmlFile = new StreamSource("<Project><Name>sample</Name></Project>");

It compiles, but I got this:

"no protocol: sample"

Thanks for reading I´ll apreciate you opinion

Upvotes: 1

Views: 5964

Answers (1)

ug_
ug_

Reputation: 11440

The reason why that doesnt work is the constructor your using is StreamSource(String systemId). The String constructor on StreamSource doesnt take xml.

Use the constructor StreamSource(Reader reader) and make an reader, such as

new StreamSource(new StringReader("xml here"))

or you can use the constructor StreamSource(InputStream inputStream) as

new StreamSource(new ByteArrayInputStream("xml here".getBytes()))

Upvotes: 5

Related Questions