Oni1
Oni1

Reputation: 1505

Defining an XSD complexType with same attribute and element name

How can I define a complexType in a XSD, which can have an attribute and an element with the same name?

For example:

<configuration>
   <configure name="variable1" value="val1"/>
   <configure name="variableList">
       <value>val1</value>
       <value>val2</value>
       <value>val3</value>
   </configure>
</configuration>

How could write an XSD for this?

Upvotes: 1

Views: 1398

Answers (1)

kjhughes
kjhughes

Reputation: 111726

Nothing special has to be done to define an element that has an attribute with the same name as the element. The following XSD will validate your XML:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="configuration">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="configure"
                    minOccurs="0" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="value" type="xs:string"
                          minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
            <xs:attribute name="name" type="xs:string"/>
            <xs:attribute name="value" type="xs:string"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

If you want the type of configure to vary based on the value of name, then use conditional type assignment (requires XSD 1.1), or, better, just differentiate the elements names themselves (works with XSD 1.0 and 1.1):

XML

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:noNamespaceSchemaLocation="try.xsd">
   <configure name="variable1" value="val1"/>
   <configureList name="variable2">
       <value>val1</value>
       <value>val2</value>
       <value>val3</value>
   </configureList>
</configuration>

XSD

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="configuration">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="configure"
                    minOccurs="0" maxOccurs="unbounded">
          <xs:complexType>
            <xs:attribute name="name" type="xs:string"/>
            <xs:attribute name="value" type="xs:string"/>
          </xs:complexType>
        </xs:element>
        <xs:element name="configureList"
                    minOccurs="0" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="value" minOccurs="0"
                          maxOccurs="unbounded"
                          type="xs:string"/>
            </xs:sequence>
            <xs:attribute name="name" type="xs:string"/>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

Upvotes: 2

Related Questions