Reputation: 2165
I am having difficulty understanding how to write a recursive XSD schema for a simple self-similar XML data tree.
I have an idea for the node schema, but not much clue how to make the schema recursive.
Here is an example of the XML, which is a financial risk spec document:
<CG SYM="ROOT" B="-1" S="-1">
<CG SYM="IOU-AllContracts" B="100" S="100" P="100">
<CG SYM="IOU100MAY14" B="-1" S="-1" P="50"/>
</CG>
</CG>
All the nodes are CG nodes, and may contain only CG nodes, to any recursion depth.
I think I have the CG (Contract/Group) Node definition figured out, including some restrictions that I want to put on the contained attribute values. B (BuyLimit) and S (SellLimit) range -1 to whatever, P (Position) is any int, SYM (Symbol) must have no whitespace:
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
elementFormDefault="qualified">
<xs:element name="CG">
<xs:complexType>
<xs:attribute name="SYM" type="xs:string" use="required">
<xs:restriction base="xs:string">
<xs:whiteSpace value="collapse"/>
</xs:restriction>
</xs:attribute>
<xs:attribute name="B" type="xs:integer" use="required">
<xs:restriction base="xs:integer">
<xs:minInclusive value="-1">
</xs:restriction>
</xs:attribute>
<xs:attribute name="S" type="xs:integer" use="required">
<xs:restriction base="xs:integer">
<xs:minInclusive value="-1">
</xs:restriction>
</xs:attribute>
<xs:attribute name="P" type="xs:integer" >
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:schema>
Thanks very much in advance for any help with this.
Upvotes: 2
Views: 2490
Reputation: 23637
You should declare that your CG
accepts an optional nested CG
. You can use the ref
attribute to refer to your element declaration:
<xs:element name="CG">
<xs:complexType>
<xs:sequence>
<xs:element ref="CG" minOccurs="0"/>
</xs:sequence>
<xs:attribute name="SYM" use="required">
....
</xs:element>
A XSD containing the element declaration below will validate the sample instance you provided:
<xs:element name="CG">
<xs:complexType>
<xs:sequence>
<xs:element ref="CG" minOccurs="0"/>
</xs:sequence>
<xs:attribute name="SYM" use="required">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:whiteSpace value="collapse"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="B" use="required">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="-1"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="S" use="required">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="-1"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="P" type="xs:integer"/>
</xs:complexType>
</xs:element>
Upvotes: 4