I have found a lot of examples like this:
public static boolean validateXMLSchema(String xsdPath, String xmlPath){
try {
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File(xsdPath));
Validator validator = schema.newValidator();
validator.validate(new StreamSource(new File(xmlPath)));
} catch (IOException | SAXException e) {
System.out.println("Exception: "+e.getMessage());
return false;
}
return true;
}
}
showing how to validate xml files over xsd, and I figured out that it's not so easy to do the same using dtd files. I have a bunch of xml files using different types of dtd (dtd files are in another location) with format:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE name SYSTEM "name.dtd">
<name>
.
.
.
</name>
How should I validate, similarly as with example above, using dtd (passing local xml and dtd paths)?
If you use a SAX parser, you may want to look into the org.xml.sax.EntityResolver
interface. You create a class that implements this interface and call .setEntityResolver(yourResolver)
on your XMLReader
. Most SAX Parsers will validate your XML automatically if a DTD is available, otherwise you may have to set the validation
feature to true
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.