Search code examples
xmlxsdxsd-validationxmlschema

XML schema's recursion of sequence of choices


I have been stumped on this problem. I'm trying to create a schema for xml with some complex recursion. I'll give an example:

<GenerationStack id="scattered_walls">
    <Noise type="perlin" gmin="0" gmax="1" size="10">
        <Noise type="binary_white" gmin="0" gmax="1" pmin="0.75" pmax="1">
            <Block id="wall_stone" pmin="0.75" pmax="1"/>
            <Block id="tile_stone" pmin="0" pmax="0.5"/>
        </Noise>
        <Block id="tile_stone" pmin="0" pmax="0.5"/>
    </Noise>
</GenerationStack>

The idea is for Noise elements to be able to contain any combination of Block and Noise elements. I have found multiple things regarding refs and types but when trying those visual studio says:Severity Code Description Project File Line Suppression State Warning The 'http://www.w3.org/2001/XMLSchema:Noise' element is not declared. For this schema:

<schema xmlns="http://www.w3.org/2001/XMLSchema" >
    <element name="GenerationStack">
        <complexType>
            <sequence minOccurs="1" maxOccurs="unbounded" >
                <choice>
                    <element name="Noise">
                        <complexType>
                            <sequence minOccurs="1" maxOccurs="unbounded" >
                                <choice>
                                    <element ref="Noise"/> <!--element part shows the message.-->
                                    <element ref="Block"/> <!--element part shows the message but with block.-->
                                </choice>
                            </sequence>
                        </complexType>
                    </element>
                    <element name="Block">
                        <complexType>
                            <!--Still need attributes here-->
                        </complexType>
                    </element>
                </choice>
            </sequence>
            <attribute name="id" type="string"/>
        </complexType>
    </element>
</schema>

If anyone can put me on the right track that would be great. Thank you for reading my post.


Solution

  • To define a recursive schema you need to use <element ref="..."/>, and to use <element ref="..."/>, the element declaration it refers to must be global - that is, it must be a child of <xs:schema>.