問題描述
我正在嘗試將一個相當復雜的 XML 模式解析加載到 Java 中的 Schema 對象中,這樣我就可以對 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.
我的代碼如下所示:
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>
...等等.當我嘗試加載架構時,出現很多錯誤.基于與此相關的另一個問題,我似乎需要指定一個資源解析器,但這不是應該默認處理的事情嗎?
...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?
最后,當我使用 XMLSpy 或類似工具加載架構時,它工作正常,我可以毫無問題地驗證 XML 實例.
Finally, when I load the schema with XMLSpy or similar, it works fine and I can validate XML instances with no problem.
推薦答案
我認為使用StreamSource,沒有指定基址,是你問題的根源.
I think that the use of StreamSource, without specifying the base location, is the source of your problem.
解析器無法知道主架構在哪里,因此無法解析 common/MessageBase.xml.
The parser has no way of knowing where the main schema is, so it can't resolve common/MessageBase.xml.
使用兩個參數的構造函數并傳入一個 SystemID,它是您開始的路徑名.
Use the two-argument constructor and pass in a SystemID that is the pathname where you're starting from.
查看 StreamSource 的 javadoc.
See the javadoc for StreamSource.
這篇關于使用導入和包含在 Java 中解析模式?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!