Skip to main content

XML Attributes

XML attributes are designed to add information about a specific XML element, i.e. they are used to define properties of elements.


An XML attribute is defined as a name-value pair.

<element-name attribute1 attribute2> 

where attribute1 and attribute2 are expressed as name="value".


"value" must be single ('value') or double ("value") quoted.

Single Quoted Attribute

<person gender="female">
<book publisher="McGraw Hill" category="Computer">

Double Quoted Attribute

<person gender='female'>
<book publisher='McGraw Hill' category='Computer'>

Attribute with both single and double quotes

If the value of the attribute itself contains double quotes, you can use single quotes:

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

viceversa, if the value of the attribute contains single quotes, you can use double quotes:

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

Otherwise you can use the character entities for double quotes:

<character name="Martin &quot;Marty&quot; Seamus McFly">

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.

For example, the same information can be represented in two equivalent ways:

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

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).

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

Element Attribute Rules

XML Attributes must follow these rules:

  • An attribute name must not appear more than once in the same start-tag or empty-element tag.
  • An attribute must be declared in the Document Type Definition (DTD) using an Attribute-List Declaration.
  • Attribute values must not contain direct or indirect entity references to external entities.
  • The replacement text of any entity referred to directly or indirectly in an attribute value must not contain a less than sign (<)