gpt4 book ai didi

java - 使用 javax.xml.validation.Validator : cannot resolve types come from 2nd XSD 针对 XSD 进行 XML 验证

转载 作者:行者123 更新时间:2023-12-01 18:20:16 25 4
gpt4 key购买 nike

我正在尝试编写一种根据 XSD 验证 XML 的方法。就我而言,我有多个 XSD 文件。

当我使用 IntelliJ IDEA 等工具从我的主 XSD 生成示例 XML 时,一切看起来都很好:示例 XML 已生成并且看起来符合我的预期。所以我认为我的 XSD 文件没问题。

这是我的简化主 XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:ds="http://www.w3.org/2000/09/xmldsig#">

<xsd:import schemaLocation="xmldsig-core-schema.xsd" namespace="http://www.w3.org/2000/09/xmldsig#" />

<xsd:element name="Message">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="messageId" type="xsd:string" />
<xsd:element ref="ds:Signature" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="Id" type="xsd:string" use="optional"/>
</xsd:complexType>
</xsd:element>
</xsd:schema>

我下载了 xmldsig-core-schema.xsd 并将其与 XSD 文件放在同一目录中。

我得到的错误:

org.xml.sax.SAXParseException: src-resolve: Cannot resolve the name 'ds:Signature' to a(n) 'element declaration' component.

Java 代码:

InputStream xsdStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("schema/my.xsd");
// 1. InputStream xsdSignatureStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("schema/xmldsig-core-schema.xsd");

Source[] sources = new StreamSource[1];
sources[0] = new StreamSource(xsdStream);
// 2. sources[1] = new StreamSource(xsdSignatureStream);

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// 3. schemaFactory.setResourceResolver(new ClasspathResourceResolver());
Schema schema = schemaFactory.newSchema(sources);

Validator validator = schema.newValidator();

String xmlString = "...";
StringReader xmlStringReader = new StringReader(xmlString)
Source source = new StreamSource(xmlStringReader);
validator.validate(source);

因此,javax.xml.validation.Validator 似乎没有看到我的第二个 XSD 文件。因此,我尝试在初始化 javax.xml.validation.Schema 时添加它,但它没有帮助(请参阅注释行 1. 和 2.)。

我还尝试创建并添加外部 ResourceResolver (请参阅注释行 3。),但它没有帮助。

评论:我使用的流已正确初始化,文件路径良好,我可以从流中读取内容并将其记录为字符串。

我想念这里什么?

最佳答案

我有同样的错误: org.xml.sax.SAXParseException: src-resolve: Cannot resolve the name 'ds:Signature' to a(n) 'element declaration' component.<code></code>

<code>
<p>And wasted several hours trying to handle it somehow.
Try to remove from "xmldsig-core-schema.xsd" all content between:</p>
</code><pre><code><?xml version="1.0" encoding="utf-8"?>
</code></pre>
<p>and</p>
<schema

这是那个地方的 DOCTYPE 定义,我的假设是,解析器无法正确处理它。

关于java - 使用 javax.xml.validation.Validator : cannot resolve types come from 2nd XSD 针对 XSD 进行 XML 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60304496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com