SirKM
SirKM

Reputation: 70

How to Determine XML Element's Children Based on Value of Attribute

I'm using Eclipse IDE to build an XML Schema for processing by JAXB, but I'm getting a validation error on the following:

    <xsd:element name="testEl">
        <xsd:complexType>
            <xsd:choice>
                <xsd:sequence>
                    <xsd:element name="testElChild">
                        <xsd:complexType>
                            <xsd:sequence>
                                <xsd:element name="tec1"/>
                                <xsd:element name="tec2"/>
                            </xsd:sequence>
                            <xsd:attribute name="type" use="required" fixed="yes"/>
                        </xsd:complexType>
                    </xsd:element>
                </xsd:sequence>
                <xsd:sequence>
                    <xsd:element name="testElChild">
                        <xsd:complexType>
                            <xsd:sequence>
                                <xsd:element name="tec3"/>
                                <xsd:element name="tec4"/>
                            </xsd:sequence>
                            <xsd:attribute name="type" use="required" fixed="no"/>
                        </xsd:complexType>
                    </xsd:element>
                </xsd:sequence>
            </xsd:choice>
        </xsd:complexType>
    </xsd:element>

Basically, I'm trying to specify that if the type attribute of element testElChild has a value of "yes" then it should contain child elements tec1 and tec2, but if the type attribute has a value of "no" then it should contain child elements tec3 and tec4.

What is wrong with the above schema and/or how do I go about accomplishing the intention with valid XML schema?

Upvotes: 1

Views: 249

Answers (1)

cdan
cdan

Reputation: 3576

It would help much that you show the validation error you get. I can only assume something about the fact you have the same element name testElChild in both choices.

To fix it, I recommend you follow two of the best practices in writing XML schemas:

  • Avoid anonymous types: it is easier to troubleshoot if you start with named types instead of anonymous types; then, when everything works and you are still determined to use anonymous types, you could translate with anonymous types (if used only once);
  • Use polymorphism instead of xsd:choice: you define an abstract type TestElChild for instance, and one extension type per choice you had, e.g. NoTypeTestElChild and YesTypeTestElChild.

It may be tedious at first but will same you some trouble on the long term. If you have issues writing the XSD according to these practices, let us know.

Upvotes: 1

Related Questions