XML Tutorial menu

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

xml
<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

xml
<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

xml
<quote by='Ali "the teacher" Khan'>Practice every day.</quote>

Element or Attribute?

The same data can be written both ways:

Example

xml
<student gender="female">
  <name>Ayesha</name>
</student>

Example

xml
<student>
  <gender>female</gender>
  <name>Ayesha</name>
</student>

Both are correct. But attributes have limits:

ElementsAttributes
Can hold several valuesYes, repeat the elementNo, only one value
Can have child structureYesNo, plain text only
Easy to add to laterYesHarder
Good forThe actual dataIDs 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
<?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 id is an attribute: it identifies the student but is not really "data"
  • A student can have many phones, so phones are elements, not one attribute
  • currency describes the fee, so it is an attribute of <fee>

A program reading this could print:

Output
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?

Learn XML with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp