XML Attributes

XML elements can have attributes. By the use of attributes we can add the information about the element.

XML attributes enhance the properties of the elements.

Note: XML attributes must always be quoted. We can use single or double quote.

Let us take an example of a book publisher. Here, book is the element and publisher is the attribute.

<book publisher="Tata McGraw Hill"></book>


<book publisher='Tata McGraw Hill'></book>

Metadata should be stored as attribute and data should be stored as element.

<book category="computer">
<author> A & B </author>

Data can be stored in attributes or in child elements. But there are some limitations in using attributes, over child elements.

Why should we avoid XML attributes

  • Attributes cannot contain multiple values but child elements can have multiple values.
  • Attributes cannot contain tree structure but child element can.
  • Attributes are not easily expandable. If you want to change in attribute's vales in future, it may be complicated.
  • Attributes cannot describe structure but child elements can.
  • Attributes are more difficult to be manipulated by program code.
  • Attributes values are not easy to test against a DTD, which is used to define the legal elements of an XML document.

Difference between attribute and sub-element

In the context of documents, attributes are part of markup, while sub elements are part of the basic document contents.

In the context of data representation, the difference is unclear and may be confusing.

Same information can be represented in two ways:

1st way:

<book publisher="Tata McGraw Hill"> </book>

2nd way:

<publisher> Tata McGraw Hill </publisher>

In the first example publisher is used as an attribute and in the second example publisher is an element.

Both examples provide the same information but it is good practice to avoid attribute in XML and use elements instead of attributes.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +