简体   繁体   中英

Specify unique element in xml

Can someone figure out what is wrong with my schema because I can add duplicate PersonID with my schema:

<xs:element name="Persons" minOccurs="1" maxOccurs="1">
      <xs:complexType>
        <xs:sequence>
          <xs:element name="Person" minOccurs="1" maxOccurs="unbounded">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="PersonID" minOccurs="1" maxOccurs="1">
                  <xs:simpleType>
                    <xs:restriction base="xs:int">
                      <xs:minExclusive value="0"/>
                    </xs:restriction>
                  </xs:simpleType>
                </xs:element>
                <xs:element name="JoinedDate" type="xs:date" minOccurs="1" maxOccurs="1"/>
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:sequence>
      </xs:complexType>
      <xs:unique name="UniquePeronID">
        <xs:selector xpath="Person" />
        <xs:field xpath="@PersonID" />
      </xs:unique>
    </xs:element>

and my xml something like:

<Persons>
     <Person>
       <PersonID>69674</PersonID>
       <JoinedDate>2006-08-25</JoinedDate>
    </Person>
    <Person>
       <PersonID>69674</PersonID>
       <JoinedDate>2006-08-25</JoinedDate>
    </Person>
</Persons>

I read the following ref but did not help me: How do I ensure unique element values in an XML schema?

https://msdn.microsoft.com/en-us/library/ms256146(v=vs.110).aspx

XML XSD Schema - Enforce Unique Attribute Values in Schema

http://support.liquid-technologies.com/KB/a79/creating-a-unique-constrant-with-an-xsd.aspx

I noticed that they have 'mstns:' in the xpath but in my case my schema does not have it eg

<xs:field xpath="@PersonID" />

That's specifying a PersonID attribute (that's what the @ means), so your schema is looking for duplicate attributes. You'll need to rephrase that to refer to the child element.

Try this instead:

<xs:field xpath="PersonID" />

Your xs:unique constraint will then work as expected.

Minor note: If Persons is intended to be a top-level element in the XSD, remove minOccurs and maxOccurs as they are not allowed to appear on top-level element definitions.

See also Unique constraint in XML Schema

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM