29

I needed to define an XML element that has no sub-elements or any content at all, and has no attributes.

This is what I am doing:

<xs:element name="myEmptyElement" type="_Empty"/>
<xs:complexType name="_Empty">
</xs:complexType>

This appears to work fine, but I have to wonder if there is a way to do this without having to declare a complex type. Also, if there is anything wrong with what I have, please let me know.

Anticipating that someone might be curious why I would need such an element: It is for a SOAP operation that does not require any parameter values.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
John S
  • 21,212
  • 8
  • 46
  • 56

2 Answers2

47

(1) You could avoid defining a named xs:complexType:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="myEmptyElement">
    <xs:complexType/>
  </xs:element>
</xs:schema>

(2) You could use a xs:simpleType instead of a xs:complexType:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="myEmptyElement">
    <xs:simpleType>
      <xs:restriction base="xs:string">
        <xs:maxLength value="0"/>
      </xs:restriction>
    </xs:simpleType>
  </xs:element>
</xs:schema>

(3) You could use fixed="" [credit: @Nemo]:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="myEmptyElement" type="xs:string" fixed=""/>
</xs:schema>

(4) But note that if you avoid saying anything about the content model:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="myEmptyElement"/>
</xs:schema>

You'll be allowing any attributes on and any content in myEmptyElement.

Community
  • 1
  • 1
kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • This is for a SOAP web service and I use soapUI to test. When soapUI automatically generates requests, it generates `` for #1, but `?` for #2 & #3. – John S Dec 24 '13 at 04:01
  • I wondered if something like #2 would be a way to use `xs:simpleType`, but it's ironic that it is more verbose than using `xs:complexType`. I also don't like that it is saying the content is a string, albeit an empty string. – John S Dec 24 '13 at 04:02
  • I guess something like `` was too much to ask for. Therefore, I will be going with #1. Since I have only one such element, it is not worth defining a named type. – John S Dec 31 '13 at 19:35
4

Another example could be:

<xs:complexType name="empty">
    <xs:sequence/>
</xs:complexType>
<xs:element name="myEmptyElement" type="empty>

or

<xs:element name="myEmptyElement">
    <xs:simpleType>
        <xs:restriction base="xs:string">
            <xs:enumeration value=""/>
        </xs:restriction>
    </xs:simpleType>
</xs:element>

or

<xs:element name="myEmptyElement">
    <xs:complexType>
        <xs:complexContent>
            <xs:restriction base="xs:anyType"/>
        </xs:complexContent>
    </xs:complexType>
</xs:element>