Reputation: 39334
This is a pretty simple question, but my Google skills haven't gotten me the answer yet, so:
Can an XSD enforce that an element MUST BE PRESENT within a higher level element? I know that you can allow or disallow "explicit setting to nil" but that doesn't sound like the same thing.
For example:
<parentTag>
<childTag1>
... stuff
</childTag1>
<childTag2> <!-- FAIL VALIDATION IF a childTag2 isn't in parentTag!!! -->
... stuff
</childTag2>
</parentTag>
If so, what is the syntax?
Upvotes: 0
Views: 141
Reputation:
Elements in an XSD are required to be present by default. If unspecified, the child element's minOccurs
property is set to 1.
That is, you must explicitly make an element optional by setting minOccurs="0"
.
Example schema
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="parentTag">
<xs:complexType>
<xs:sequence>
<xs:element name="childTag1" minOccurs="0"/> <!-- This element is optional -->
<xs:element name="childTag2"/> <!-- This element is required -->
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Testing valid XML (using xmllint)
<?xml version="1.0"?>
<parentTag>
<childTag1>
<!-- ... stuff -->
</childTag1>
<childTag2>
<!-- ... stuff -->
</childTag2>
</parentTag>
testfile.xml validates
Testing invalid XML
<?xml version="1.0"?>
<parentTag>
<childTag1>
<!-- ... stuff -->
</childTag1>
</parentTag>
testfile.xml:2: element parentTag: Schemas validity error : Element 'parentTag': Missing child element(s). Expected is ( childTag2 ). testfile.xml fails to validate
Upvotes: 2