Search code examples
xmlvalidationdtd

How can I define a self closing XML element in a DTD file?


The element that I want to define:

<testing-element code="Input"/>

The code I've put in my DTD file:

<!ELEMENT testing-element ()>
<!ATTLIST testing-element code CDATA #REQUIRED>

The problem is, that you are currently not allowed to leave the brackets from the !ELEMENT tag empty


Solution

  • You can declare the element like this:

    <!ELEMENT testing-element EMPTY>
    

    An empty pair of brackets like in your example isn't valid content model declaration syntax.

    This will allow you to specify the element either in XML-style empty element syntax

    <testing-element/>
    

    or with start- and end-element tags:

    <testing-element></testing-element>
    

    There's no way to require empty-element syntax (owing to XML's SGML heritage).

    Technically, you can also use empty end-element syntax on any element that happens to accept empty content eg. has a content model with all elements optional:

    <ELEMENT e (f?)>
    

    or that isn't declared at all when using lax validation.