简体   繁体   English

XML和XSD-子元素仅在选择某些父属性时才有效?

[英]XML and XSD - Sub-Elements only valid when certain Parent Attribute is selected?

Is it possible to declare in the XSD that a sub-element is only valid when the parent element has a specific attribute selected? 是否可以在XSD中声明子元素仅在父元素选择了特定属性时才有效?

So for example in the xml: 因此,例如在xml中:

<dropdown style="radiobuttons">
<button>my first choice</button>
<button>my second choice</button>
<button>my third choice</button>
</dropdown>

<dropdown style="checkboxes">
<checkbox>my first choice</checkbox>
<checkbox>my second choice</checkbox>
<checkbox>my third choice</checkbox>
</dropdown>

but the below would be invalid / the schema would not support it as the button element is to be only used with style="radiobutton" 但以下内容将是无效的/架构将不支持它,因为button元素只能与style =“ radiobutton”一起使用

<dropdown style="checkboxes">
<button>my first choice</button>
<button>my second choice</button>
<checkbox>my third choice</checkbox>
</dropdown>

I'm aware that the choices would need to be controlled in the xsd by xs:enumeration 我知道选择将需要在xsd中由xs:enumeration控制

XSD 1.0 does not support that sort of conditional type assignment, but XSD 1.1 does: XSD 1.0不支持这种条件类型分配,但是XSD 1.1支持:

XSD 1.1 Solution XSD 1.1解决方案

<?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"
  vc:minVersion="1.1">

  <xs:element name="dropdown">
    <xs:alternative test="@style eq 'radiobuttons'" type="RadioButtonsType" />
    <xs:alternative test="@style eq 'checkboxes'" type="CheckBoxesType" />
  </xs:element>

  <xs:complexType name="RadioButtonsType">
    <xs:sequence>
      <xs:element name="button" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="CheckBoxesType">
    <xs:sequence>
      <xs:element name="checkbox" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

</xs:schema>

However, note that you can avoid the need for XSD 1.1 and conditional type assignment here very naturally simply by using different container elements for button elements and checkbox elements rather than using dropdown for both. 但是,请注意,您可以很自然地避免对XSD 1.1和条件类型赋值的需要,只需在button元素和checkbox元素中使用不同的容器元素,而不是对两者都使用dropdown

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM