Skip to main content

XML DTD Elements Vs. Attributes

In XML, there are no rules that define when to use attributes or when to use child elements.

XML Elements vs. Attributes

Attributes are used to distinguish between elements with the same name, when you don't want to create a new element for every situation. So, using an attribute can add a little more detail in differentiating two or more similar elements.

<character name="Martin 'Marty' Seamus McFly">
<character>
<name>Martin 'Marty' Seamus McFly</name>
</character>

In the first example, name is an attribute while in the second one it is an element.

There are no rules about when to use attributes or when to use elements in XML.

But overuse of XML attributes can create confusion in your document.

Prefer XML Elements to XML Attributes

Notice that:

  • attributes can't contain multiple values (while elements can).
  • attributes can't contain tree structures (while elements can).
  • attributes aren't easily expandable for future changes.
  • attributes are more difficult to be manipulated by program code.
  • attribute values are not easy to test against a DTD (which is used to define the legal elements of an XML document).
note

In the end, my suggestion is to prefer XML elements whenever possible