XSD中itemName唯一性设置异常:重复值未触发校验错误求助
itemName Validation in Your XSD Ah, I’ve run into this exact issue before! The problem almost always boils down to misplacing the uniqueness constraint or messing up the XPath paths in your XSD. Let’s break this down step by step.
First, let’s recap your XML structure for clarity:
<records> <name>John</name> <items> <itemName>Dryer</itemName> <itemPrice>20</itemPrice> </items> <items> <itemName>Dryer</itemName> <itemPrice>20</itemPrice> </items> </records>
Why Your Current XSD Isn’t Working
The most common mistake here is defining the uniqueness constraint inside the items element instead of at the parent records level. If you put <xs:unique> inside items, it only checks for uniqueness within a single items node—and since each items has only one itemName, there’s no way to trigger a duplicate error.
The Correct XSD Solution
You need to define the xs:unique constraint on the records element (the parent of all items nodes) so it applies to every itemName across all items entries. Here’s the fixed XSD:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="records"> <xs:complexType> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="items" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="itemName" type="xs:string"/> <xs:element name="itemPrice" type="xs:decimal"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> <!-- Critical: Uniqueness constraint defined at the records level --> <xs:unique name="uniqueItemName"> <!-- Selector: Targets all <items> nodes under <records> --> <xs:selector xpath="items"/> <!-- Field: Checks the value of <itemName> inside each selected <items> --> <xs:field xpath="itemName"/> </xs:unique> </xs:element> </xs:schema>
Key Details to Note:
- Constraint Scope: By placing
<xs:unique>directly under therecordselement (outside its<xs:complexType>), we ensure the rule applies to allitemsnodes in the entire document. - XPath Accuracy:
- The
xs:selectorusesitemsto pick every childitemsnode ofrecords. - The
xs:fieldusesitemNameto target the value inside eachitemsnode. Double-check that these paths match your XML’s element names exactly (XPath is case-sensitive!).
- The
- Tool Compatibility: Make sure your XML validator supports XSD 1.0 (most modern tools do—this constraint is part of the core standard).
Testing the Fix
When you validate your sample XML with this XSD, you should get an error like:
Duplicate unique value [Dryer] declared for identity constraint 'uniqueItemName'
Which is exactly what you want—this confirms the duplicate itemName is being caught correctly.
内容的提问来源于stack exchange,提问作者Ironman

