2015-09-11 134 views
0

我需要使用XSD验证传入的XML到我的系统。下面是一个示例XML和XSD。XSD验证子元素的唯一性

<?xml version="1.0" encoding="utf-8" standalone="no"?> 
<root> 
    <records> 
     <record> 
      <content>record text</content> 
      <childlist> 
       <child> 
        <chilldref>left_child</chilldref> 
        <content>child 1 text</content> 
       </child> 
       <child> 
        <chilldref>middle_child</chilldref> 
        <content>child 2 text</content> 
       </child> 
       <child> 
        <chilldref>right_child</chilldref> 
        <content>child 3 text</content> 
       </child> 
      </childlist> 
     </record> 
    </records> 
</root> 


<?xml version="1.0" encoding="Windows-1252"?> 
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xs:element name="root"> 
     <xs:complexType> 
      <xs:all> 
       <xs:element name="records"> 
        <xs:complexType> 
         <xs:sequence> 
          <xs:element name="record"> 
           <xs:complexType> 
            <xs:all minOccurs="0"> 
             <xs:element name="content" type="xs:string" /> 
             <xs:element name="childlist" minOccurs="1" maxOccurs="1"> 
              <xs:complexType> 
               <xs:sequence> 
                <xs:element maxOccurs="3" name="child" minOccurs="1"> 
                 <xs:complexType> 
                  <xs:all minOccurs="0"> 
                   <xs:element name="chilldref" type="childreftype" minOccurs="1" /> 
                   <xs:element name="content" type="xs:string" /> 
                  </xs:all> 
                 </xs:complexType> 
                </xs:element> 
               </xs:sequence> 
              </xs:complexType> 
              <xs:unique name="uniqueref"> 
               <xs:selector xpath="child" /> 
               <xs:field xpath="childref" /> 
              </xs:unique> 
             </xs:element> 
            </xs:all> 
           </xs:complexType> 
          </xs:element> 
         </xs:sequence> 
        </xs:complexType> 
       </xs:element> 
      </xs:all> 
     </xs:complexType> 
    </xs:element> 
    <xs:simpleType name="childreftype"> 
     <xs:restriction base="xs:string"> 
      <xs:enumeration value="left_child" /> 
      <xs:enumeration value="right_child" /> 
      <xs:enumeration value="middle_child" /> 
     </xs:restriction> 
    </xs:simpleType> 
</xs:schema> 

这里我检查是否有一个'childlist'元素至少有一个'child'元素。对于'child'元素'childref'属性是强制性的,它应该是'childreftype'类型。 现在我需要确保没有两个“child”元素具有相同的“childref”。任何关于如何用XSD实现这一点的想法。

**更新: 将<xs:unique>元素置于'childlist'范围之后,此工作正常。

回答

2

对于约束“在一个X,必须是具有Z的相同值没有两个Y元素”,你需要一个xs:在元素声明唯一约束为X:

<xs:unique name="x-y-z"> 
    <xs:selector xpath="Y"/> 
    <xs:field xpath="Z"/> 
</xs:unique> 

在你情况Y =“孩子”和Z =“chilldref”(原文如此),但X可以是根,记录,记录或孩子列表 - 你还没有详细地指出问题,足以让我知道。