Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

performing xml validation against xsd

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?

like image 818
volcano Avatar asked Mar 18 '11 12:03

volcano


People also ask

Can we validate XML documents against a schema?

You can validate your XML documents against XML schemas only; validation against DTDs is not supported. However, although you cannot validate against DTDs, you can insert documents that contain a DOCTYPE or that refer to DTDs.

How you will validate XML document using schema?

XML documents are validated by the Create method of the XmlReader class. To validate an XML document, construct an XmlReaderSettings object that contains an XML schema definition language (XSD) schema with which to validate the XML document. The System. Xml.

How do I reference XML in XSD?

Reference the XSD schema in the XML document using XML schema instance attributes such as either xsi:schemaLocation or xsi:noNamespaceSchemaLocation. Add the XSD schema file to a schema cache and then connect that cache to the DOM document or SAX reader, prior to loading or parsing the XML document.


2 Answers

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;
}
like image 95
Steve Bennett Avatar answered Oct 12 '22 20:10

Steve Bennett


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)));
like image 40
bdoughan Avatar answered Oct 12 '22 22:10

bdoughan