Search code examples
xmlparsingxsdxml-validation

How to allow an attribute on an element with string content?


I'm trying to write an XSD for the following XML:

  <users>
    <user id='u1'>A</user>
    <user id='u2'>B</user>
    <user id='u3'>C</user>
  </users>

Here is what I have so far:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <xsd:element name="users">
          <xsd:complexType>
            <xsd:sequence>
              <xsd:element name="user" maxOccurs="unbounded" type="xsd:string">
                <xsd:attribute name="id" type="xsd:string"/>
              </xsd:element>
            </xsd:sequence>
          </xsd:complexType>
        </xsd:element>
</xsd:schema>

But it returns errror:

Element '{http://www.w3.org/2001/XMLSchema}element': The content is not valid. Expected is (annotation?, ((simpleType | complexType)?, (unique | key | keyref)*))

The id attribute is the id of user. Any idea how I can fix this?


Solution

  • Here is how to define an element with simpleContent (xsd:string) and an attribute in XSD:

    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <xsd:element name="users">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="user" maxOccurs="unbounded">
              <xsd:complexType>
                <xsd:simpleContent>
                  <xsd:extension base="xsd:string">
                    <xsd:attribute name="id" type="xsd:string"/>
                  </xsd:extension>
                </xsd:simpleContent>
              </xsd:complexType>
            </xsd:element>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    </xsd:schema>
    

    (Your error has nothing to do with maxOccurs being unbounded. It had to do with the content model of your user element.)