考虑一个 XML 文档,它像下面这样以多个模式开始(这不是特定于 Spring 的问题;这只是一个方便的 XML 文档示例):
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:osgi="http://www.springframework.org/schema/osgi"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd
http://www.springframework.org/schema/osgi
http://www.springframework.org/schema/osgi/spring-osgi.xsd">
我想验证文档,但我事先不知道文档作者将使用哪些命名空间。我信任文档作者,所以我愿意下载任意架构 URL。如何实现我的 validator ?
我知道我可以在调用 setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", new String[] {...})
时使用 DocumentBuilderFactory 实例指定我的模式但在文档被解析之前我不知道架构 URL。
当然,我可以在解析文档后自行提取 XSD URL,然后通过指定 "http://java.sun.com/xml/jaxp/properties/schemaSource"
的 validator 运行它。如上所述,但肯定已经有一个自动执行此操作的实现?
最佳答案
我还没有证实这一点,但你可能会发现 Use JAXP Validation API to create a validator and validate input from a DOM which contains inline schemas and multiple validation roots有用。
特别是,
factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
关于java - 针对多个任意模式验证 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7638457/