XML Schema:在complexType中使用属性定义

时间:2013-07-28 15:21:43

标签: java xml xsd sax xml-validation

我在使用SAX解析器进行XML验证时遇到了一些问题。这是一个简单的XML Schema,用于解决问题:

<?xml version="1.0"?>
<xs:schema targetNamespace="urn:test"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified"
    xmlns="urn:test">

    <xs:element name="root">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="content" type="ContentType"
                    maxOccurs="unbounded" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:complexType name="ContentType">
        <xs:simpleContent>
            <xs:extension base="xs:string">
                <xs:attribute ref="title" use="required" />
            </xs:extension>
        </xs:simpleContent>
    </xs:complexType>

    <xs:attribute name="title" type="xs:string" />

</xs:schema>

这是一个非常简单的XML文件,在我看来应该对我的架构有效:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root xmlns="urn:test">
        <content title="Title">
            Content comes here...
        </content>
</root>

有趣的是,当我尝试解析此XML文件时,收到以下验证错误:

cvc-complex-type.3.2.2: Attribute 'title' is not allowed to appear in element 'content'.

但是,如果我从XML文件中删除 content 元素的 title 属性,我仍会收到验证错误:

cvc-complex-type.4: Attribute 'title' must appear on element 'content'.

我不知道问题是什么。当然,这只是一个提出问题的简单例子。我想了解这种行为的原因。此外,找到一个解决方案会很高兴。在这种情况下,我不确定执行验证的Java代码是否很重要,如果有必要,我会稍后发布。

任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:2)

title属性的全局声明将该属性放在目标名称空间urn:test中。这也意味着您必须在架构和实例文档中限定对属性的引用。默认情况下,非限定属性没有名称空间。

<xs:schema targetNamespace="urn:test"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
xmlns="urn:test" xmlns:test="urn:test" >
....    
<xs:complexType name="ContentType">
    <xs:simpleContent>
        <xs:extension base="xs:string">
            <xs:attribute ref="test:title" use="required" />
        </xs:extension>
    </xs:simpleContent>
</xs:complexType>

<xs:attribute name="title" type="xs:string" />

<root xmlns="urn:test" xmlns:test="urn:test" >
    <content test:title="Title">
        Content comes here...
    </content>
</root>

这一切都非常微妙,当我尝试在ecplise中验证原始实例文档时,我得到两个非常令人困惑的错误:

  1. title属性无法出现在内容元素上。这是指对属性的无限制使用,以及
  2. title元素必须出现在内容元素上。这是指缺少合格的test:title属性。
  3. 当然,错误消息可以使用更多的上下文信息。

相关问题