XML XSD Schema - Enforce Unique Attribute Values in Schema

前端 未结 3 1352
温柔的废话
温柔的废话 2020-12-04 23:22

Lets say I have a schema that defines the following XML:


    Value 1
    Value 2&l         


        
相关标签:
3条回答
  • 2020-12-05 00:00

    @BatteryBackupUnit has the right idea, but the syntax is more like:

    <xs:element name="Values">
      <xs:complexType>
        <xs:sequence>
          <xs:element ref="Add" maxOccurs="unbounded"/>
        </xs:sequence>
      </xs:complexType>
      <xs:unique name="UniqueAddKey">
        <xs:selector xpath="Add" /> 
        <xs:field xpath="@Key" /> 
      </xs:unique>
    </xs:element>
    
    0 讨论(0)
  • 2020-12-05 00:00

    More on Michael Kay's answer: If your schema (XSD) declares a namespace, you must include this in your selection.xpath. If you are using Microsoft Visual Studio 2010, you may find a namespace automatically declared.

    <xs:schema id="MyData"
        targetNamespace="http://tempuri.org/MyData.xsd"
        elementFormDefault="qualified"
        xmlns="http://tempuri.org/MyData.xsd"
        xmlns:mstns="http://tempuri.org/MyData.xsd"
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
    >
        ...
        <xs:unique name="UniqueAddKey">
            <xs:selector xpath="mstns:Add" /> 
            <xs:field xpath="@Key" /> 
        </xs:unique>
    </xs:schema>
    
    0 讨论(0)
  • 2020-12-05 00:25

    you can achieve this by using xs:unique

    <xs:element name="Instrument">
      <xs:complexType>
       <xs:all>
        <xs:unique name="ModuleId">
          <xs:selector xpath="./*" /> 
          <xs:field xpath="@id" /> 
        </xs:unique>
       </xs:all>
      </xs:complexType>
    </xs:element>
    

    The above example will enforce a unique attribute "id" for all Instrument Elements. there's also xs:key, which can be used to establish a Primary Key - Foreign Key relationship: http://www.datypic.com/books/defxmlschema/chapter17.html

    0 讨论(0)
提交回复
热议问题