XSD element with both attributes and child elements

Ste83 picture Ste83 · Mar 30, 2012 · Viewed 61.5k times · Source

I want to know the correct syntax for defining an element containing both attributes and child elements (if possible). For example:

<component type="A" binding="B">
  <operation name="X">
    <input type="C" />
  </operation>

  <event name="Y">
    <output type="D" />
  </event>
</component>

As you can see, both elements component, operation and event have both attributes and child element. Is it possible to define this in XSD? How?

Thank you very much!

Answer

Petru Gardea picture Petru Gardea · Mar 30, 2012

This is one possible way to define an XSD matching your XML; when learning XSD, you could enroll the help of a tool that infers the XSD for you, starting from one or more XML sample files.

<?xml version="1.0" encoding="utf-8"?>
<!--W3C Schema generated by QTAssistant/W3C Schema Refactoring Module (http://www.paschidev.com)-->
<xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="component">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="operation">
          <xsd:complexType>
            <xsd:sequence>
              <xsd:element name="input">
                <xsd:complexType>
                  <xsd:attribute name="type" type="xsd:string" use="required" />
                </xsd:complexType>
              </xsd:element>
            </xsd:sequence>
            <xsd:attribute name="name" type="xsd:string" use="required" />
          </xsd:complexType>
        </xsd:element>
        <xsd:element name="event">
          <xsd:complexType>
            <xsd:sequence>
              <xsd:element name="output">
                <xsd:complexType>
                  <xsd:attribute name="type" type="xsd:string" use="required" />
                </xsd:complexType>
              </xsd:element>
            </xsd:sequence>
            <xsd:attribute name="name" type="xsd:string" use="required" />
          </xsd:complexType>
        </xsd:element>
      </xsd:sequence>
      <xsd:attribute name="type" type="xsd:string" use="required" />
      <xsd:attribute name="binding" type="xsd:string" use="required" />
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

As you walkthrough this, you may start tweaking min/maxOccurs, use (required/optional), reusing definitions, etc. A generated XSD is a good starting point, but typically ends up being edited one way or another...