I have an XML schema with my "video" element and "youtube" element inside:
<xs:element name="video">
<xs:complexType>
<xs:sequence>
<xs:element ref="youtube" minOccurs="0" maxOccurs="1"/>
</xs:sequence>
<xs:attribute name="file" type="xs:string"/>
</xs:complexType>
</xs:element>
and I want to add to available video types another element "param":
<xs:element name="param">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required"/>
<xs:attribute name="value" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
I would have "param" element inside next to "youtube".
Restrictions:
like this:
<video>
<youtube file = "aaa"/>
<param name="a1" value"b1"/>
<param name="a2" value"b2"/>
</video>
How to maintain this restrictions in this schema?
If I do something like this:
<xs:sequence>
<xs:element ref="youtube" minOccurs="0" maxOccurs="1"/>
<xs:element ref="param" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
if the sequence is specified like this
<xs:sequence>
<xs:element ref="youtube" minOccurs="0" maxOccurs="1"/>
<xs:element ref="param" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
it determines that param has to be after youtube - but I don't want to specify the sequence
Here is XSD schema:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="video">
<xs:complexType>
<xs:choice minOccurs="1" maxOccurs="2">
<xs:element ref="youtube"/>
<xs:element ref="param" minOccurs="1" maxOccurs="unbounded"/>
</xs:choice>
</xs:complexType>
</xs:element>
<xs:element name="youtube">
<xs:complexType>
<xs:attribute name="file" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
<xs:element name="param">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required"/>
<xs:attribute name="value" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>
Example (well-formed and valid) XML:
<?xml version="1.0" encoding="UTF-8"?>
<video>
<youtube file="aaa"/>
<param name="a1" value="b1"/>
<param name="a2" value="b2"/>
</video>
There is one issue with above solution. xs:choice allows two youtube elements. There is xs:all element, which solve that, but unfortunately it's impossible to get param's maxOccurs more than one with it (xs:all limitation).
In other words there is no 100% solution using XML Schema 1.0. If above is not sufficient you can use another schema language such as RELAX NG or Schematron.
edit:
In XML Schema 1.1 (superset of XML Schema 1.0) you can write video element as:
<xs:element name="video">
<xs:complexType>
<xs:all>
<xs:element ref="youtube"/>
<xs:element ref="param" minOccurs="0" maxOccurs="unbounded"/>
</xs:all>
</xs:complexType>
</xs:element>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With