XML Free Tutorial

Web based School

XML Attributes


In this guide, we will learn about the XML attributes with the help of examples.
What are XML attributes?
XML attributes are a way to add additional data to the XML element. Attributes contain data in form of name & value pairs.
For example: Here we have added an attribute name brand and value Ford Figo to the element <car brand="Ford Figo"> <name>Ford Figo 1.2P Ambiente MT</name> <horsepower>65 kW @ 6,300 rpm</horsepower> </car> XML example with more than one attributes In the above example we have a single attribute associated with the element , however we can have more than one attribute associated to the same element as well. Lets take an example – <car brand="Ford Figo" category="Subcompact car"> <name>Ford Figo 1.2P Ambiente MT</name> <horsepower>65 kW @ 6,300 rpm</horsepower> </car> In the above example brand and category are the attributes associated with element car.
Rules for XML attributes
Some of the rules related to the XML attributes have already been discussed in the XML syntax guide, however lets recall those rules here along with some other rules.
1. Attributes are name & value pairs. The attribute name should not be in quotes, however the attribute value must always be in quotes (single or double) <car brand="Ford Figo"> --> Correct <car "brand"=Ford Figo> --> Incorrect 2. XML element can have more than one attributes. This we have already seen in the above example, where brand and category attributes are linked to the element . 3. Attributes cannot contain duplicate multiple values. <car brand="Ford Figo" brand="Subcompact car"> -->wrong XML attributes vs XML Elements Lets have a look at the following two examples – Example 1: Here brand is an attribute <car brand="Ford Figo"> <name>Ford Figo 1.2P Ambiente MT</name> <horsepower>65 kW @ 6,300 rpm</horsepower> </car> Example 2: Here brand is an element <car> <brand>Ford Figo</name> <name>Ford Figo 1.2P Ambiente MT</name> <horsepower>65 kW @ 6,300 rpm</horsepower> </car> In both the examples, the XML document contain the same data. However you should always prefer XML element over XML attribute. Why? Lets discuss it in the following section.
Why you should prefer XML element over attribute?
In the above two examples, we learned that the same information can be contained in a XML document by using XML element in place of attribute. The reason we do this is because attributes have certain limitations in XML –
1. attributes cannot have multiple values while elements can.
2. Using attributes we cannot achieve the XML tree structure that we can achieve using element and sub-elements.
3. Attributes values are difficult to test against a DTD
4. Elements are easy to be handled by the programming language compared to the attributes.


Previous Next