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?
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.
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.
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.
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;
}
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With