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.
Metadata should be stored as attribute and data should be stored as element.
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:
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.