Home >>XML Tutorial >XML Attributes

XML Attributes

XML Attributes

XML elements may have attributes to them. We may attach details about the item by the use of attributes.

XML attributes improve component properties.

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

Or

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

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


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

Data may be stored in attributes or in elements for child. But the use of attributes, over child elements, has certain limitations.

Why should we avoid XML attributes

  • Values don't have multiple values so multiple values can be contained in child components.
  • Attributes are not capable of containing tree structure but child element may.
  • Attributes don't expand easily. If you want to change the vales of an attribute
  • This could be difficult in the future.
  • Attributes are not capable of representing structure but child components can.
  • Attributes are easier to control by system code.

Difference between attribute and sub-element

Attributes are part of the markup when it comes to data, while sub-elements are part of the quality of the actual text.

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

We can represent the same details in two ways:

1st way:


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

2nd way:


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

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

Both examples provide the same information but avoiding attributes in XML and using elements instead of attributes is good practice.


No Sidebar ads