Search code examples
xmlxsdoxygenxmlxml-1.1

Correct usage of xs:alternative in XML 1.1


This is how I'm defining an element with alternative types.

alternative.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
  elementFormDefault="qualified"
  vc:minVersion="1.1">

    <xs:complexType name="DefaultType">
        <xs:sequence>
            <xs:element name="string" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="OtherType">
        <xs:sequence>
            <xs:element name="number" type="xs:integer"/>
        </xs:sequence>
    </xs:complexType>

    <xs:element name="root">
        <xs:alternative test="@switchTo = 'OtherType'" type="OtherType"/>
        <xs:alternative type = "DefaultType"/>
    </xs:element>

</xs:schema>

sampleA.xml

<?xml version="1.1" encoding="UTF-8"?>

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:noNamespaceSchemaLocation="alternative.xsd">

    <string>
        Sample
    </string>

</root>

sampleB.xml

<?xml version="1.1" encoding="UTF-8"?>

<root switchTo="OtherType"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:noNamespaceSchemaLocation="alternative.xsd">

    <number>
        23571113
    </number>

</root>

First none of my validators supported it, so I switched to Oxygen XML for evaluation. It validates everything, and type resolution and validation works for every alternative, but I'm getting an error:

Attribute 'switchTo' is not allowed to appear in element 'apply'.

I know the attribute is not defined for element 'root', but I also don't know where I should define it! I've tried various places in an exploring manner, with no luck. Thank you for your time.


Solution

  • If you set up different complex types for the element then your complex types need to declare the attribute you want to give to the element:

    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
        elementFormDefault="qualified"
        vc:minVersion="1.1">
    
        <xs:complexType name="DefaultType">
            <xs:sequence>
                <xs:element name="string" type="xs:string"/>
            </xs:sequence>
            <xs:attribute name="switchTo" type="xs:string"/>
        </xs:complexType>
    
        <xs:complexType name="OtherType">
            <xs:sequence>
                <xs:element name="number" type="xs:integer"/>
            </xs:sequence>
            <xs:attribute name="switchTo" type="xs:string"/>
        </xs:complexType>
    
        <xs:element name="root">
            <xs:alternative test="@switchTo = 'OtherType'" type="OtherType"/>
            <xs:alternative type = "DefaultType"/>
        </xs:element>
    
    </xs:schema>