Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Schema (XSD) - How to specify parent element to contain at least one child element?

Tags:

xml

schema

xsd

I have an XML schema (XSD) that defines an element as mandatory (call it the parent); this parent has, lets say, five child elements, which can all be optional, BUT AT LEAST ONE child element must occur.

How can i specify this in the xsd?

To clarify: The children are different elements and optional. For example.

<Parent>
   <Child1>contents are different to other siblings and arbitrary</Child1>
   <Child2>can be text, a simple element, or another complex element</Child2>
   <Child3>etc.. etc</Child3> 
</Parent>

<xs:complexType name="Parent">
  <xs:sequence>
    <xs:element minOccurs="0" name="Child1" type="xs:string"/>
    <xs:element minOccurs="0" name="Child2" />
    <xs:element minOccurs="0" name="Child3" />
  </xs:sequence>
</xs:complexType>

Even though every child is optional, the parent needs to have at least one child.

like image 271
joedotnot Avatar asked Mar 22 '10 07:03

joedotnot


People also ask

How do you make an element required in XSD?

The "use" property in the XSD definition is used to specify if the attribute is optional or mandatory. To specify that an attribute must be present, use="required" (Note: use may also be set to "prohibited", but we'll come to that later).

How do you define attributes for simple element in XSD?

Attributes are defined within an XSD as follows, having name and type properties. An Attribute can appear 0 or 1 times within a given element in the XML document. Attributes are either optional or mandatory (by default the are optional).


2 Answers

There is always the direct approach:

<xs:complexType name="Parent">
  <xs:choice>
    <xs:sequence>
      <xs:element name="Child1"/>
      <xs:element name="Child2" minOccurs="0"/>
      <xs:element name="Child3" minOccurs="0"/>
    </xs:sequence>
    <xs:sequence>
      <xs:element name="Child2"/>
      <xs:element name="Child3" minOccurs="0"/>
    </xs:sequence>
    <xs:sequence>
      <xs:element name="Child3"/>
    </xs:sequence>
  </xs:choice>
</xs:complexType>
like image 74
WReach Avatar answered Nov 15 '22 09:11

WReach


Using assertions (I think it is only available in XSD 1.1) it is possible to do the following:

<xs:element name="Parent">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="Child1" type="xs:string" minOccurs="0"/>
            <xs:element name="Child2" minOccurs="0"/>
            <xs:element name="Child3" minOccurs="0"/>
        </xs:sequence>
        <xs:assert test="count(*)>=1"/>
    </xs:complexType>
</xs:element>
like image 25
Max Avatar answered Nov 15 '22 11:11

Max