简体   繁体   中英

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?

So for example in the 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"

<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 1.0 does not support that sort of conditional type assignment, but XSD 1.1 does:

XSD 1.1 Solution

<?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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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