Reputation: 5897
I have been trying to construct an XSD file to validate some xml
XSD Example
<xs:element name="person" type="persontype"/>
<xs:complexType name="persontype">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
XML Example
<persontype>
<firstname/>
<lastname/>
</persontype>
How can I construct the xsd to require that the 'firstname' is mandatory, and the 'lastname' is not even necessary for the xml to be valid, and that the sequence does not have to be in order, so long as the hierarchy is respected?
End Result of XMLs which could be encountered, and which I would like to be considered valid according to my final xsd.
Valid Scenario 1
<persontype>
<firstname/>
</persontype>
Valid Scenario 2
<persontype>
<lastname/>
<firstname/>
</persontype>
Appreciate your time with the help.
Upvotes: 0
Views: 183
Reputation: 1889
I've adapted this from the XML Schema tutorial on indicators:
<xs:element name="person">
<xs:complexType>
<xs:all>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string" minOccurs="0"/>
</xs:all>
</xs:complexType>
</xs:element>
If you use the all
indicator, the sequence of your elements can be arbitrary, but by default each element has to occur exactly one time.
To make lastname optional, you can change the default by providing the minOccurs
indicator and setting it to zero.
This will allow you to optionally specify a single lastname per person, with any order of elements.
Upvotes: 1