XML Schema:唯一性约束

时间:2012-10-09 18:18:43

标签: xml xsd schema

经过几个小时的尝试,我仍然无法得到这个简单的例子。目标很简单:带有Notes的xml-Document仅在每个Node分配了唯一NoteID时才有效。

这是我的Notes.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            targetNamespace="http://xml.netbeans.org/schema/Notes"
            xmlns:tns="http://xml.netbeans.org/schema/Notes"
            elementFormDefault="qualified">
    <xsd:element name="Notes">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="Note" maxOccurs="unbounded">
                    <xsd:complexType>
                        <xsd:sequence>
                            <xsd:element name="NoteID" type="xsd:positiveInteger"/>
                            <xsd:element name="Content"  type="xsd:string"/>
                        </xsd:sequence>
                    </xsd:complexType>
                    <xsd:unique name="newKey">
                        <xsd:selector xpath="."/>
                        <xsd:field xpath="NoteID"/>
                    </xsd:unique>
                </xsd:element>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
</xsd:schema>

Notes.xml

<?xml version="1.0" encoding="UTF-8"?>
<ns0:Notes  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
            xmlns:ns0='http://xml.netbeans.org/schema/Notes'
            xsi:schemaLocation='http://xml.netbeans.org/schema/Notes Notes.xsd'>
    <ns0:Note>
        <ns0:NoteID>1</ns0:NoteID>
        <ns0:Content>this</ns0:Content>
    </ns0:Note>
    <ns0:Note>
        <ns0:NoteID>1</ns0:NoteID>
        <ns0:Content>is a</ns0:Content>
    </ns0:Note>
    <ns0:Note>
        <ns0:NoteID>3</ns0:NoteID>
        <ns0:Content>test</ns0:Content>
    </ns0:Note>
</ns0:Notes>

我不知道为什么这会证实:

$ xmllint --noout -schema Notes.xsd Notes.xml 
Notes.xml validates

1 个答案:

答案 0 :(得分:2)

xsd:unique位置错误,您需要xpath中明确的名称空间前缀。

这有效:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            targetNamespace="http://xml.netbeans.org/schema/Notes"
            xmlns:tns="http://xml.netbeans.org/schema/Notes"
            elementFormDefault="qualified">
  <xsd:element name="Notes">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="Note" maxOccurs="unbounded">
          <xsd:complexType>
            <xsd:sequence>
              <xsd:element name="NoteID" type="xsd:positiveInteger"/>
              <xsd:element name="Content"  type="xsd:string"/>
            </xsd:sequence>
          </xsd:complexType>
        </xsd:element>
      </xsd:sequence>
    </xsd:complexType>
    <xsd:unique name="newKey">
      <xsd:selector xpath="tns:Note"/>
      <xsd:field xpath="tns:NoteID"/>
    </xsd:unique>
  </xsd:element>
</xsd:schema>