forcing attribute in XSD Schema to be the primary key ( and sorted)
In the XML shown below, Is there a way to create a schema that will 开发者_Python百科describe the XML so that the id value will increase by 1 with the addition of each Book node. The goal is to use id as a primary key whose minimum value = 1. Also, id values should be are sorted in an ascending manner.
<Books>
<Book id="1"></Book>
<Book id="2"></Book>
<Book id="3"></Book>
<Book id="4"></Book>
...
</Books>
No. you cannot do that in xsd.
xsd defines the xml schema not the xml data. you will need to do that in your code that parses the xml data.
I think the closest you can get is this:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="Books">
<xs:complexType>
<xs:sequence>
<xs:element name="Book">
<xs:complexType>
<xs:attribute name="id" type="id_type" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:key name="PK_BookID">
<xs:selector xpath="Books/Book" />
<xs:field xpath="@id" />
</xs:key>
<xs:unique name="BookIdUnique">
<xs:selector xpath="Books/Book" />
<xs:field xpath="@id" />
</xs:unique>
</xs:element>
<xs:simpleType name="id_type">
<xs:restriction base="xs:integer">
<xs:minInclusive value="1" />
</xs:restriction>
</xs:simpleType>
</xs:schema>
I cannot think of any way to enforce sorting and an id sequence without gaps but as this.__curious_geek already stated XSD is not meant for this.
精彩评论