Home > Blockchain >  XSD follow one element format or another
XSD follow one element format or another

Time:04-01

I have to validate a complexType that can follow two given formats. <section> must appear twice. <section> can follow the first format both times, the second format both times, or a combination of format1 and format2 once each.

<!--FORMAT 1-->
<section>
    <!-- <section> can follow one of two formats -->
    <!-- Elements will appear in sequence-->
    <title>I'm a title</title>
    <authors>
        <author>Helen Sharp</author>
        <author>Yvonne Rogers</author>
        <author>Jenny Preece</author>
    </authors>
    <publisher year="2019">Wiley</publisher>
</section>

<!--FORMAT 2-->
<section>
    <!-- Elements will appear in sequence-->
    <isbn>
        <isbn>1119547253</isbn>
        <isbn>9781119547259</isbn>
    </isbn>
    <notes> I'm a note </notes>
    <format>Print book</format>
    <edition>5</edition>
    <subjects>
        <subject>Hello</subject>
    </subjects>
</section>

I thought maybe I could use <xs:choice> and then <xs:sequence> inside of that but I was getting the following error: Element 'choice' Is Invalid, Misplaced, Or Occurs Too Often.

My code so far looks like this:

<xs:element name="root">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="section" minOccurs="2" maxOccurs="2">
                <xs:complexType>
                    <xs:choice> <!--This choice will be for format 1-->
                        <xs:sequence>
                            <!--other validation for format1-->
                        </xs:sequence>
                    </xs:choice>
                    
                    <xs:choice> <!--This choice will be for format 2-->
                        <xs:sequence>
                            <!--other validation for format2-->
                        </xs:sequence>
                    </xs:choice>
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>

I can kind of understand why this would not work but this is the only thing I could think of doing. Maybe there is something I'm missing? Any help would be really great :)

CodePudding user response:

Replace

            <xs:choice> 
                <xs:sequence>
                    <!--other validation for format1-->
                </xs:sequence>
            </xs:choice>
            
            <xs:choice> 
                <xs:sequence>
                    <!--other validation for format2-->
                </xs:sequence>
            </xs:choice>

by

            <xs:choice>
                <xs:sequence>
                    <!--other validation for format1-->
                </xs:sequence>
                <xs:sequence>
                    <!--other validation for format2-->
                </xs:sequence>
            </xs:choice>
  • Related