使用导入和包含解析 Java 中的架构?
我正在尝试将相当复杂的 XML 模式解析加载到 Java 中的 Schema 对象中,以便我可以对 XML 消息进行一些验证。
我的代码看起来与此类似:
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new StreamSource(new File("schema/schema.xsd")));
我的架构有很多导入:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="base_1">
<xs:import namespace="base_1" schemaLocation="common/MessageBase.xsd"/>
</xs:schema>
...等。当我尝试加载架构时,出现很多错误。基于与此相关的另一个问题,看起来我需要指定一个资源解析器,但这不是应该默认处理的东西吗?
如果是这样,是否需要将架构放置在相对于运行我正在编写的应用程序的位置或相对于基本架构文件的特定目录中?
最后,当我使用 XMLSpy 或类似工具加载架构时,它工作正常,并且我可以毫无问题地验证 XML 实例。
I'm attempting to parse load a rather complicated XML schema into a Schema object in Java so I can do some validation on XML messages.
My code looks similar to this:
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new StreamSource(new File("schema/schema.xsd")));
My schema has quite a few imports:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="base_1">
<xs:import namespace="base_1" schemaLocation="common/MessageBase.xsd"/>
</xs:schema>
...etc. When I attempt to load the schema, I get lots of errors. Based on one other question related to this, it looks like I need to specify a resource resolver, but isn't this something that should be handled by default?
If so, is there a specific directory I need to put the schema in relative to where I run the application I'm writing or relative to the base schema file?
Finally, when I load the schema with XMLSpy or similar, it works fine and I can validate XML instances with no problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用 URL 而不是 StreamSource,则不需要资源解析器。
There is no need for a resource resolver if you use an URL instead of a StreamSource.
我认为使用 StreamSource 而不指定基本位置是问题的根源。
解析器无法知道主模式在哪里,因此无法解析 common/MessageBase.xml。
使用两个参数的构造函数并传入一个 SystemID,它是您开始的路径名。
请参阅 StreamSource 的 javadoc。
I think that the use of StreamSource, without specifying the base location, is the source of your problem.
The parser has no way of knowing where the main schema is, so it can't resolve common/MessageBase.xml.
Use the two-argument constructor and pass in a SystemID that is the pathname where you're starting from.
See the javadoc for StreamSource.
为了解析导入的 XSD,您必须将架构工厂与资源解析器关联:
有关更多详细信息,您可以查看此答案。
In order to resolve the imported XSDs you have to associate the schema factory with a resource resolver:
For further details you can look at this answer.