I have to write an XML schema (in XSD 1.0) to validate a given document.
In this document, there is an element called box
that either:
has two required attributes,
name
andweight
and some other optional one, no contenthas one required attribute,
name
, no other attributes, and several element as content (includingbox
elements).
For example:
<box name="box_1"> <!-- type 2 -->
<box name="box_2"> <!-- type 2 -->
<box name="box_3" weight="10" height="5" /> <!-- type 1 -->
<box name="box_4" weight="15" /> <!-- type 1 -->
</box>
<box name="box_5"> <!-- type 2 -->
<box name="box_6" weight="21" /> <!-- type 1 -->
</box>
</box>
<box name="box_7" weight="21" /> <!-- type 1 -->
The issue is that:
I cannot define
box
with two different types (xmllint does not recognise which type is used and invalidate anybox
that doesn't have the attributeweight
)I cannot add
<xs:attributes>
in a<xs:choice>
I cannot use
<xs:alternative>
because I have to use XSD 1.0I cannot make
weight
optional, it has to be requiredI cannot modify the given xml document
This, for example, does not work:
<xs:complexType name="closet">
<xs:choice maxOccurs="unbounded">
<xs:element name="box" type="TboxComplex" />
<xs:element name="box" type="TboxSimple" />
</xs:choice>
</xs:complexType>
<xs:complexType name="TboxComplex">
<xs:choice maxOccurs="unbounded">
<xs:element name="box" type="TboxComplex" />
<xs:element name="box" type="TboxSimple" />
</xs:choice>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
<xs:complexType name="TboxSimple">
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="weight" type="xs:integer" use="required" />
<xs:attribute name="height" type="xs:integer" use="optional" />
</xs:complexType>
> xmllint --schema room.xsd room.xml
room.xml:9: element box: Schemas validity error : Element 'box', attribute 'weight': The attribute 'weight' is not allowed.`
room.xml:9: element box: Schemas validity error : Element 'box', attribute 'height': The attribute 'height' is not allowed.
room.xml:9: element box: Schemas validity error : Element 'box': Missing child element(s). Expected is ( box ).
Could you help me find a way to define that element without needing to change the xml document or switch to XSD 1.1, please? Thank you in advance!
XSD 1.0 is not capable of defining this constraint. You will need to use some other validation technology such as XSD 1.1, RelaxNG, or Schematron; or you might be able to do it with XSD 1.0 if you are prepared to add
xsi:type
attributes to your XML instance.