XML Attributes

Home » Scripting » XML » XML Attributes

What are XML Attributes

XML elements can have attributes, just like HTML.

Attributes are designed to contain data related to a specific element.

Attribute values must always be quoted. Either single or double quotes can be used.

XML attributes are used to describe XML elements, or to provide additional information about elements.

HTML example:

<img src="home.gif">
<a href="google.com">

XML example:

<file type="png">
<person id="245">

Attributes are used to provide information that is not a part of the content of the XML document. This means that in the example above the “id” isn’t important for the reader, but it might be very important for the software using the XML file.

Quoting XML attributes

While attributes must always be quoted, either single or double quotes can be used.

For a student’s gender, the %lt;student> element can be
written like this:

<student gender="female"> 

Or like this:

<student gender='female'> 

If the attribute value itself contains double quotes:

<gangster name='Napoleon I "The Little Corporal" of France'> 

Or use character entities

<gangster name='Napoleon I "The Little Corporal" of France'> 

XML Elements vs. Attributes

There are no fixed rules about when to use attributes to describe data, and when to use elements.

Attributes are handy in HTML, but in XML you should try to avoid them, as long as the same information can be expressed using elements (elements can be used instead of attributes).

The following XML documents contain exactly the same information, but in different ways.

Attributes example

<person gender="female" age="32">

Elements example

<person gender="female" age="32">

There are no rules about when to use attributes or when to use elements in XML. However most developers would prefer it if you would use elements instead of attributes.

Another example that shows why elements are preferred:


Date can be extended like so


Why use elements?

  • attributes can not contain multiple values (elements can)
  • attributes are not expandable (for future changes)
  • attributes can not describe structures / tree structures (like child elements can)
  • attributes are more difficult to manipulate by program code
  • attribute values are not easy to test against a DTD

Very bad example

<message day="12" month="04" year="2017"
to="John" from="Jane" heading="Reminder"
body="Call me when you can">

The exception to the attribute rule – The Metadata ID references are assigned to elements,they can be used to identify XML elements

Metadata (data about data) should be stored as attributes, and the data itself should (a good practice) be stored as elements