【问题标题】:how to make an attribute unique in xml schema?如何使属性在 xml 模式中唯一?
【发布时间】:2020-04-05 18:19:55
【问题描述】:

我想让一个元素的属性像主键一样是唯一的。如何制作?

【问题讨论】:

    标签: xml xsd


    【解决方案1】:

    这样的事情应该可以工作:

    <xs:element name="books" maxOccurs="unbounded">
       <xs:complexType>
          <xs:sequence>
             <xs:element name="book" maxOccurs="unbounded">
                <xs:complexType>
                   <xs:attribute name="isbn" type="xs:string"/>
                </xs:complexType>
             </xs:element>
          </xs:sequence>
       </xs:complexType>
       <xs:unique name="unique-isbn">
          <xs:selector xpath="book"/>
          <xs:field xpath="@isbn"/>
       </xs:unique>
    </xs:element>
    

    基本上,您可以使用 &lt;xs:unique&gt; 元素定义“唯一性”约束,并定义该唯一性应应用于哪个 XPath。

    请参阅 W3Schools 的entry on &lt;xs:unique&gt; 了解更多信息。

    【讨论】:

      【解决方案2】:

      注意: 如果您有不同的命名空间,这将不起作用。然后你需要完整的 XPath 表达式:

      这可能是这样的:

      <xs:unique name="unique-isbn">
            <xs:selector xpath="theOtherNamespace:book"/>
            <xs:field xpath="@isbn"/>
      </xs:unique>
      

      【讨论】:

        【解决方案3】:

        注意:限制基数必须是“ID”。

        <xs:element name="vahicles">
          <xs:complexType>
            <xs:sequence>
               <xs:element ref="vahicle" minOccurs="1" maxOccurs="unbounded"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        
        
        
        <xs:element name="vahicle">
            <xs:complexType>
                <xs:sequence>
                    <xs:element ref="shop_name" />
                    <xs:element ref="address" />
                </xs:sequence>
                <!-- defining an attribute in vahicle element. -->
            <xs:attribute ref="vshop_id" use="required" />
            </xs:complexType>
        </xs:element>
        
        <!-- adding some restriction on the attribute -->
        <!-- restriction base must be ID. -->
        <xs:attribute name="vshop_id">
            <xs:simpleType>
                <xs:restriction base="xs:ID">
                <xs:pattern value="vsp\d{3}" />
            </xs:restriction>
            </xs:simpleType>
        </xs:attribute>
        
        
        
        <xs:element name="shop_name" type="xs:string"/>
        <xs:element name="address" type="xs:string"/>
        

        【讨论】:

          猜你喜欢
          • 2016-01-10
          • 1970-01-01
          • 1970-01-01
          • 2018-09-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-05
          • 1970-01-01
          相关资源
          最近更新 更多