XSD schema attempt to make attribute value unique
I have been trying to use xs:unique with no success so far. I have the following simple schema:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns="http://testuri/test.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://testuri/test.xsd"
elementFormDefault="qualified"
id="XMLSchema1">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="items">
&l开发者_如何学Got;xs:complexType>
<xs:sequence>
<xs:element name="item" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="id" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Using this the following simple XML file is validated:
<?xml version="1.0" encoding="utf-8" ?>
<root xmlns="http://testuri/test.xsd">
<items>
<item id="1"/>
<item id="1"/>
<item id="1"/>
</items>
</root>
Now let's say we want to make attribute id unique. I was thinking of simply changing the schema to:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema
xmlns="http://testuri/test.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://testuri/test.xsd"
elementFormDefault="qualified" id="XMLSchema1">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="items">
<xs:complexType>
<xs:sequence>
<xs:element name="item" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="id" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:unique name="itemKey">
<xs:selector xpath="items/item"/>
<xs:field xpath="@id"/>
</xs:unique>
</xs:element>
</xs:schema>
However the xml above still gets validated.
I am most certain that the problem lies on the xpath of the selector. Any ideas?
I think you must qualify the xpath expression with namespace prefixes (since XPath 1.0 has no notion of default namespace). So add a namespace declaration for your target namespace:
<xs:schema
xmlns="http://testuri/test.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://testuri/test.xsd"
xmlns:p="http://testuri/test.xsd"
elementFormDefault="qualified" id="XMLSchema1">
and then use that prefix in your xpath expression:
<xs:unique name="itemKey">
<xs:selector xpath="p:items/p:item"/>
<xs:field xpath="@id"/>
</xs:unique>
I have not verified this, though.
精彩评论