XML Elements and Attributes
Elements and attributes are the two ways to put data into an XML document.
Elements
An element is everything from a start tag to its end tag, including what is inside:
Example
<book>
<title>Learn Web Basics</title>
<author>Sana Malik</author>
<year>2025</year>
<price>950</price>
</book>An element can contain:
- Text, like
<year>2025</year> - Other elements, like
<book>above - Both, called mixed content:
<p>Read <b>this</b> first.</p> - Nothing, an empty element:
<sold-out/>
Attributes
An attribute gives extra information about an element. It sits inside the start tag as name="value":
Example
<book id="B101" language="ur">
<title>Karachi Ki Kahaniyan</title>
</book>Attribute values must always be in quotes, single or double. If the value contains a double quote, use single quotes around it:
Example
<quote by='Ali "the teacher" Khan'>Practice every day.</quote>Element or Attribute?
The same data can be written both ways:
Example
<student gender="female">
<name>Ayesha</name>
</student>Example
<student>
<gender>female</gender>
<name>Ayesha</name>
</student>Both are correct. But attributes have limits:
| Elements | Attributes | |
|---|---|---|
| Can hold several values | Yes, repeat the element | No, only one value |
| Can have child structure | Yes | No, plain text only |
| Easy to add to later | Yes | Harder |
| Good for | The actual data | IDs and small facts about the data |
A good rule: put data in elements, and information about the data (metadata like an id, a unit or a language) in attributes.
A Well-designed Example
Example
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student id="S01">
<name>Ali Raza</name>
<course>Graphic Designing</course>
<phones>
<phone type="mobile">0300-1234567</phone>
<phone type="home">021-5550123</phone>
</phones>
<fee currency="PKR">6000</fee>
</student>
<student id="S02">
<name>Ayesha Khan</name>
<course>Web Development</course>
<phones>
<phone type="mobile">0321-7654321</phone>
</phones>
<fee currency="PKR">8000</fee>
</student>
</students>Notice:
- The
idis an attribute: it identifies the student but is not really "data" - A student can have many phones, so phones are elements, not one attribute
currencydescribes the fee, so it is an attribute of<fee>
A program reading this could print:
S01: Ali Raza, Graphic Designing, PKR 6000, 2 phones S02: Ayesha Khan, Web Development, PKR 8000, 1 phone
Avoid These Mistakes
- Do not put a list inside one attribute, like
phones="0300...,021..." - Do not use the same attribute twice in one element; it is an error
- Do not use vague names like
<data1>,<field2>
Exercise
Exercise
In <price currency="PKR">500</price>, what is currency?
