Search code examples
xmlxsdxml-validation

XML schema multiple attribute


I'm trying to create a required elements which has different sub elements. Example XMl file like this:

<datamodel>
    <info name="user">
        <userRight>add user</userRight>
    </info>
    <info name="admin">
        <role>manager</role>
    </info>
</datamodel>

I currently have the following xml schema.

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="datamodel">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="info" maxOccurs="unbounded" minOccurs="0" >
          <xs:complexType>
            <xs:sequence>
              <xs:element type="xs:string" name="userRight" minOccurs="0"/>
              <xs:element type="xs:string" name="role" minOccurs="0"/>
            </xs:sequence>
            <xs:attribute type="xs:string" name="name" use="optional" fixed="user"/>
          </xs:complexType>
        </xs:element>
        <xs:element name="info" maxOccurs="unbounded" minOccurs="0">
          <xs:complexType>
            <xs:sequence>
              <xs:element type="xs:string" name="userRight" minOccurs="0"/>
              <xs:element type="xs:string" name="role" minOccurs="0"/>
            </xs:sequence>
            <xs:attribute type="xs:string" name="name" use="optional" fixed="admin"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

However given XML schema will not work with example XML file which I have. How can I modify the schema for validate such a XML?


Solution

  • You could achieve what you want with XML Schema 1.1, with the Type Alternative mechanism. It would look something like this:

    <xs:element name="info" type="xs:anyType">
        <xs:alternative test="@name='user'" type="userRightType"/>
        <xs:alternative test="@name='admin'" type="roleType"/>
    </xs:element>
    

    Next, find an XML Parser that supports XML Schema 1.1. You did not mention which language you use but I think the latest Xerces2 Java supports it.