问题
I am using XSD for XML validation. I want to add unique values constraint for the input
elements.
I have XML format like this:
<?xml version="1.0" encoding="UTF-8"?>
<test>
<definitions>
<input>Page</input>
</definitions>
<definitions>
<input>Page</input>
</definitions>
</test>
My XSD:
<xs:schema attributeFormDefault="unqualified"
elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="test">
<xs:complexType>
<xs:sequence>
<xs:element name="definitions" maxOccurs="unbounded" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:string" name="input"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
I want to know how xs:unique
should be placed.
回答1:
To place the xs:unique
element:
- Identify the scope of uniqueness (
test
) for the elements ofxs:unique/@selector
(definitions
). - Place the
xs:unique
element- within the declaration of
test
, and - after the
xs:complexType
fortest
- within the declaration of
See HERE in the XSD below:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xs:element name="test">
<xs:complexType>
<xs:sequence>
<xs:element name="definitions"
maxOccurs="unbounded" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:string" name="input"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<!-- HERE -->
<xs:unique name="definitions-input-unique">
<xs:selector xpath="definitions"/>
<xs:field xpath="input"/>
</xs:unique>
</xs:element>
</xs:schema>
Then this invalid XML
<?xml version="1.0" encoding="UTF-8"?>
<test>
<definitions>
<input>Page</input>
</definitions>
<definitions>
<input>Page</input>
</definitions>
</test>
will receive an error message such as the following:
[Error] try.xml:7:24: cvc-identity-constraint.4.1: Duplicate unique value [Page] declared for identity constraint "definitions-input-unique" of element "test".
回答2:
Just put it at the top level like this:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="test">
<xs:complexType>
<xs:sequence>
<xs:element name="definitions" maxOccurs="unbounded" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:string" name="input"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:unique name="input-values">
<xs:selector xpath="./definitions"/>
<xs:field xpath="input"/>
</xs:unique>
</xs:element>
</xs:schema>
来源:https://stackoverflow.com/questions/29003329/where-to-place-xsunique-constraint-in-xsd