XML Elements vs. Attributes

Estudies4you
XML Elements vs. Attributes
XML Attributes
XML elements can have attributes in the start tag, same like HTML.
  • In HTML and in XML attributes provide additional information about elements
For example:
<img src="rose.gif"><ahref="demo.asp">
The "src" attribute provides additional information about the <img> element.
  • Attributes often provide information that is not a part of the data
For example:
<file type="gif">rose.gif</file>
The file type is irrelevant to the data, but important to the software that wants to manipulate the element.
  • Attribute values must always be enclosed in quotes, either single quotes or double quotes. For a person's sex, the person tag can be written as:
<person sex="male"> or <person sex=imale'›
  • If the attribute value itself contains double quotes you can use single quotes.
For example:
<faculty name=’Kiran "kumar" V'> or you can use character entities <faculty name-'Kiranr&guot;kumar&guot; V’>.

XML Elements vs. Attributes
Take a look at these examples.
Example 1
<person sex="male">
<firstname>prabhakar</firstname>
<lastname>Raju</lastname>
</person>

Example 2
<person>
<sex>male</sex>
<firstname>Prabhakar</firstname>
 <lastname>Raju</lastname>
</person>

In the Example 1, sex is an attribute. In the Example 2, sex is an element.
Both examples provide the same information.
There are no rules about when to use attributes and when to use elements.
Attributes are handy in HTML. In XML, avoid them instead use elements.

Problems with XML Attributes
Some of the problems with using attributes are:
  • They cannot contain multiple values (elements can)
  • They cannot contain tree structures (elements can)
  • They are not easily expandable (for future changes)
  • They are difficult to read and maintain
Use elements for data.
Use attributes for information that is not relevant to the data.
Don't end up like this:
<note day="10" month="01" year="2013" to="Raj u" from="Ravi"
heading="Reminder" body="Don't forget me this weekend!"> </note>

To Top