46

我正在尝试使用 xsd 验证一个非常简单的 xml,但由于某种原因,我收到了这个错误。如果有人能解释我为什么,我将不胜感激。

XML 文件

<?xml version="1.0" encoding="utf-8"?> 
<MyElement>A</MyElement>

XSD 文件

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
        targetNamespace="http://www.example.org/Test"
        xmlns:tns="http://www.example.org/Test"
        elementFormDefault="qualified">

    <simpleType name="MyType">
        <restriction base="string"></restriction>
    </simpleType>

    <element name="MyElement" type="tns:MyType"></element>
</schema>
4

4 回答 4

42

您的架构适用于其目标命名空间,因此它在该目标命名空间中http://www.example.org/Test定义了一个具有名称的元素。但是,您的实例文档在no namespace中具有 name 的元素。这就是为什么验证解析器告诉您它找不到该元素的声明,您没有为没有命名空间中的元素提供架构。MyElementhttp://www.example.org/TestMyElement

您要么需要更改架构以根本不使用目标命名空间,要么需要更改实例以使用例如<MyElement xmlns="http://www.example.org/Test">A</MyElement>.

于 2012-11-10T10:20:28.543 回答
4

在进行上述 Martin 建议的更改后,我仍然遇到同样的错误。我不得不对我的解析代码进行额外的更改。我正在通过 DocumentBuilder 解析 XML 文件,如 oracle 文档中所示: https ://docs.oracle.com/javase/7/docs/api/javax/xml/validation/package-summary.html

// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));

问题是 DocumentBuilder 默认情况下不支持命名空间。以下附加更改解决了该问题:

// parse an XML document into a DOM tree
DocumentBuilderFactory dmfactory = DocumentBuilderFactory.newInstance();
dmfactory.setNamespaceAware(true);

DocumentBuilder parser = dmfactory.newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));
于 2020-12-15T14:59:01.407 回答
1

我的 XXX 元素出现此错误,这是因为我的 XSD 根据 javax.xml.bind v2.2.11 格式错误。我认为它使用的是较旧的 XSD 格式,但我没有费心去确认。

我最初的错误 XSD 如下所示:

<xs:element name="Document" type="Document"/>
...
<xs:complexType name="Document">
    <xs:sequence>
        <xs:element name="XXX" type="XXX_TYPE"/>
    </xs:sequence>
</xs:complexType>

我迁移成功的良好 XSD 格式如下:

<xs:element name="Document">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="XXX"/>
        </xs:sequence>
    </xs:complexType>        
</xs:element>
...
<xs:element name="XXX" type="XXX_TYPE"/>

对于每个类似的 XSD 节点,依此类推。

于 2018-05-25T19:15:48.803 回答
0

我在使用 Maven 的 Eclipse 中使用附加信息时遇到了同样的错误

schema_reference.4: Failed to read schema document 'https://maven.apache.org/xsd/maven-4.0.0.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.

这是在复制一个新控制器之后,它的界面来自一个 Thymeleaf 示例。老实说,无论我多么小心,我仍然无法理解人们应该如何解决这个问题。在(幸运的)猜测中,我右键单击了该项目,单击了 Maven 和更新项目,这解决了问题。

于 2020-02-16T20:29:30.213 回答