Tegud.NET

XSD Element content and attributes

This is a problem I encountered whilst working on a configuration XSD at work, I wanted to have a node that had content, with an enforced type along with attributes.  An example of the XML I wanted to allow is below.

<Quotes>
    <Quote author="George W. Bush">Rarely is the questioned asked: Is our children learning?</Quote>
</Quotes>

To specify a type for the node contents as well as some attributes, we need to use a type extension, specifying the type we want for the content as the base type.   This is shown below.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="Quotes">
      <xs:complexType>
        <xs:sequence>
          <xs:element name="Quote">
            <xs:complexType>
              <xs:simpleContent>
                <xs:extension base="xs:string">
                  <xs:attribute name="author" type="xs:string" />
                </xs:extension>
              </xs:simpleContent>
            </xs:complexType>
          </xs:element>
        </xs:sequence>
      </xs:complexType>
    </xs:element>
  </xs:schema>

The XSD above will permit the XML we want, and allow content and attributes on the same node.  I'll probably do some more stuff on XSDs in the near future.

blog comments powered by Disqus