【问题标题】:Restrict XSD attribute value based on another attribute value基于另一个属性值限制 XSD 属性值
【发布时间】:2015-05-06 20:10:38
【问题描述】:

我在 XML 中有这个:

<Const Name="a" Value="1.0"/>
<Const Name="b" Value="1"/>
<Const Name="c" Value="A"/>
<Const Name="d" Value="B"/>

现在仅适用于 Name="b" ConstValue 必须为 1、2、3 或 4。不允许使用其他值。其他Const 可能包含其他值,如图所示。 如何在 XSD 中表达?

到目前为止,我有这个:

<xs:element name="Const">
   <xs:complexType>
       <xs:attribute name="Value" type="xs:string" use="required"/>
       <xs:attribute name="Name" type="xs:string" use="required"/>
   </xs:complexType>
</xs:element>

我使用 XSD 1.0,似乎:VS2013...所以“替代”对我不起作用...遗憾...

【问题讨论】:

    标签: xml xsd xsd-1.0


    【解决方案1】:

    您可以使用 XSD 1.1 的 Conditional Type Assignment

    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
      xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
      elementFormDefault="qualified"
      vc:minVersion="1.1"> 
    
      <xs:element name="Const">
        <xs:alternative test="@Name = 'a'" type="aType"/>        
        <xs:alternative                    type="otherType"/>
      </xs:element>
    
      <xs:complexType name="aType">
        <xs:sequence/>
          <xs:attribute name="Name" type="xs:string"/>
          <xs:attribute name="Value">
            <xs:simpleType>
              <xs:restriction base="xs:integer">
                <xs:minInclusive value="1"/>
                <xs:maxInclusive value="4"/>
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
      </xs:complexType>
    
      <xs:complexType name="otherType">
        <xs:sequence/>
        <xs:attribute name="Name" type="xs:string"/>
        <xs:attribute name="Value" type="xs:string"/>
      </xs:complexType>
    </xs:schema>
    

    【讨论】:

    • 对于你的 aType 我想出了这个:
    • 是的,基于正则表达式的aType 也是完全有效的。
    【解决方案2】:

    使用 xs:assert 的示例解决方案假设您使用的是 XSD 1.1

    <xs:element name="Const">
        <xs:complexType>
            <xs:attribute name="Value" type="xs:string" use="required"/>
            <xs:attribute name="Name" type="xs:string" use="required"/>
            <xs:assert test="(@Name='b' and @Value=('1', '2', '3', '4'))
                or
                (@Name='a' and @Value=('1.0', '2.0', '3.0', '4.0'))
                or
                (@Name='c')
                or
                (@Name='d')"></xs:assert>
        </xs:complexType>
    </xs:element>
    

    请注意,这只是一个示例,您可能需要对其进行更改。

    【讨论】:

      猜你喜欢
      • 2014-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      相关资源
      最近更新 更多