Search code examples
javaxmlxsdschemaxsd-1.0

In XSD schema 1.0 validation, any option available to check an element has any attributes?


In the XSD file, for an element few attributes are given as optional. Need to validate if any of the listed attributes in available in the input XML file.


Solution

  • In XSD 1.0 you can use xs:key in order to guarantee that an element has at least one attribute. Example:

    <xs:element name="elem">
        <xs:complexType>
            <xs:attribute name="a" type="xs:int" use="optional" />
            <xs:attribute name="b" type="xs:int" use="optional" />
            <xs:attribute name="c" type="xs:int" use="optional" />
            <xs:attribute name="d" type="xs:int" use="optional" />
        </xs:complexType>
        <xs:key name="attributePresent">
            <xs:selector xpath="." />
            <xs:field xpath="@*" />
        </xs:key>
    </xs:element>
    

    As an example, if you want to guarantee that at least one of b or c attributes are present in the element you can use

    <xs:field xpath="@b | @c" />