[英]xml validation with local dtd passing local xml and dtd files using java
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. 展示了如何通过xsd验证xml文件,我发现使用dtd文件做同样的事情并不容易。 I have a bunch of xml files using different types of dtd (dtd files are in another location) with format: 我有一堆使用不同类型的dtd的xml文件(dtd文件位于另一个位置),格式为:
<?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)? 与上面的示例类似,我应该如何使用dtd(传递本地xml和dtd路径)进行验证?
If you use a SAX parser, you may want to look into the org.xml.sax.EntityResolver
interface. 如果使用SAX解析器,则可能需要查看org.xml.sax.EntityResolver
接口。 You create a class that implements this interface and call .setEntityResolver(yourResolver)
on your XMLReader
. 您创建一个实现此接口的类,并在XMLReader
上调用.setEntityResolver(yourResolver)
。 Most SAX Parsers will validate your XML automatically if a DTD is available, otherwise you may have to set the validation
feature to true
. 如果DTD可用,大多数SAX解析器将自动验证XML,否则您可能必须将validation
功能设置为true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.