5

I have XML as a string and an XSD as a file, and I need to validate the XML with the XSD. How can I do this?

james.garriss
  • 12,959
  • 7
  • 83
  • 96
volcano
  • 91
  • 1
  • 2
  • 4
  • Either u need an XML file in stead of String and than you can validate the XML with XSD,there are lots of tools available like Jaxb 2.x,Xrces etc – Umesh Awasthi Mar 18 '11 at 12:19

2 Answers2

11

You can use javax.xml.validation API to do this.

public boolean validate(String inputXml, String schemaLocation)
  throws SAXException, IOException {
  // build the schema
  SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
  File schemaFile = new File(schemaLocation);
  Schema schema = factory.newSchema(schemaFile);
  Validator validator = schema.newValidator();

  // create a source from a string
  Source source = new StreamSource(new StringReader(inputXml));

  // check input
  boolean isValid = true;
  try  {

    validator.validate(source);
  } 
  catch (SAXException e) {

    System.err.println("Not valid");
    isValid = false;
  }

  return isValid;
}
thonnor
  • 1,206
  • 2
  • 14
  • 28
Steve Bennett
  • 387
  • 3
  • 13
2

You can use the javax.xml.validation APIs for this:

String xml = "<root/>";  // XML as String
File xsd = new File("schema.xsd");  // XSD as File

SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(xsd); 

SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setSchema(schema);
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.parse(new InputSource(new StringReader(xml)));
bdoughan
  • 147,609
  • 23
  • 300
  • 400