使用Xerces-j验证XML文档

时间:2022-06-02 17:15:13

I'm trying to validate an XML document using Xerces-J.

我正在尝试使用Xerces-J验证XML文档。

I want the validator to pick up and resolve any associated XSD or DTD files (using schemalocation, nonamespaceschemalocationa and DOCTYPE references). It seems the loading of these resources can be delegated to a Resolver class.

我希望验证器获取并解析任何关联的XSD或DTD文件(使用schemalocation,nonamespaceschemalocationa和DOCTYPE引用)。似乎可以将这些资源的加载委托给Resolver类。

However all the samples I've seen start off creating a validator from a schema.

然而,我见过的所有样本都是从模式创建验证器开始的。

Is it possible to drive this the other way around, ask xerces to validate the XML document, and have it load what it needs, or must I first parse the XML file looking for schema references, load them, then create a validator from the schemas?

是否有可能以相反的方式驱动它,请求xerces验证XML文档,并让它加载它需要的东西,或者我必须首先解析XML文件寻找模式引用,加载它们,然后从模式创建验证器?

In an ideal world the validator would also support xsd 1.1

在理想的世界中,验证器也支持xsd 1.1

1 个解决方案

#1


3  

You provide a parser with an EntityResolver to use when looking up <!DOCTYPE declarations or schema attributes. The most common entity resolver uses catalog files, which are essentially XML files or text files that define a dictionary of public IDs, system IDs, and URIs to physical files. See the org.apache.xml.resolver package. But you can also provide your own EntityResolver implementation.

您在查找<!DOCTYPE声明或架构属性时提供了一个具有EntityResolver的解析器。最常见的实体解析程序使用目录文件,这些文件本质上是XML文件或文本文件,用于定义公共ID,系统ID和物理文件URI的字典。请参阅org.apache.xml.resolver包。但您也可以提供自己的EntityResolver实现。

CatalogResolver resolver = new CatalogResolver();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
dbf.setFeature("http://apache.org/xml/features/validation/dynamic", true);
DocumentBuilder parser = dbf.newDocumentBuilder();
parser.setEntityResolver(resolver);
Document doc = parser.parse(someFile);

#1


3  

You provide a parser with an EntityResolver to use when looking up <!DOCTYPE declarations or schema attributes. The most common entity resolver uses catalog files, which are essentially XML files or text files that define a dictionary of public IDs, system IDs, and URIs to physical files. See the org.apache.xml.resolver package. But you can also provide your own EntityResolver implementation.

您在查找<!DOCTYPE声明或架构属性时提供了一个具有EntityResolver的解析器。最常见的实体解析程序使用目录文件,这些文件本质上是XML文件或文本文件,用于定义公共ID,系统ID和物理文件URI的字典。请参阅org.apache.xml.resolver包。但您也可以提供自己的EntityResolver实现。

CatalogResolver resolver = new CatalogResolver();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
dbf.setFeature("http://apache.org/xml/features/validation/dynamic", true);
DocumentBuilder parser = dbf.newDocumentBuilder();
parser.setEntityResolver(resolver);
Document doc = parser.parse(someFile);