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.
An empty element is an element that is complete by itself; it never contains other elements. Rather than being composed of a start tag, data, and an end tag, the empty element is a combined start and end tag.
XML elements can be defined as building blocks of an XML. Elements can behave as containers to hold text, elements, attributes, media objects or all of these. Each XML document contains one or more elements, the scope of which are either delimited by start and end tags, or for empty elements, by an empty-element tag.
The XML attribute is a part of an XML element. The addition of attribute in XML element gives more precise properties of the element i.e, it enhances the properties of the XML element. In the above syntax element_name is the name of an element which can be any name.
(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
.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With