XML Introduction
XML stands for eXtensible Markup Language. It is a way to write data as text, using tags.
What is XML?
- XML stands for eXtensible Markup Language
- It was made to store and transport data
- It is self-describing: the tag names explain the data
- You invent your own tags; XML has no fixed list of tags
- It is a W3C standard, first published in 1998
"Extensible" means you can extend it with any tags you need, such as <price>, <order> or <student>.
XML Does Not Do Anything
XML is just data in a text file. It does not show, send or calculate anything by itself. A program must read it and do something with it.
Example
<message>
<to>Ali</to>
<from>Ayesha</from>
<subject>Class timing</subject>
<body>Tomorrow's class starts at 4 pm.</body>
</message>This is a message with a sender, a receiver and text, but it does nothing until some software reads it, for example to show it in an app or send it as an SMS.
XML vs HTML
| HTML | XML | |
|---|---|---|
| Purpose | Shows data (how it looks) | Carries data (what it is) |
| Tags | Fixed: <p>, <h1>, <a> | You make your own |
| Rules | Forgiving: browsers fix mistakes | Strict: one mistake stops the program |
| Case | Not case sensitive | Case sensitive |
| End tags | Some can be left out | Always required |
XML is not a replacement for HTML. They work together: XML holds the data, and HTML can display it.
Where XML is Used
- Sitemaps (
sitemap.xml) that tell Google about your pages - RSS feeds for news sites and podcasts
- SVG images on websites
- Office files:
.docxand.xlsxare zip files full of XML - Android layouts and many app configuration files
- SOAP web services used by banks, payment gateways and governments
The XML Tree
An XML document is a tree. It has exactly one root element, and every other element sits inside it.
Example
<?xml version="1.0" encoding="UTF-8"?>
<shop>
<product>
<name>Lawn Suit</name>
<price currency="PKR">4500</price>
</product>
<product>
<name>Cotton Dupatta</name>
<price currency="PKR">1200</price>
</product>
</shop>shop
product
name: Lawn Suit
price: 4500 (currency PKR)
product
name: Cotton Dupatta
price: 1200 (currency PKR)| Word | Meaning in this example |
|---|---|
| Root | <shop>, the top element |
| Parent | <product> is the parent of <name> |
| Child | <name> and <price> are children of <product> |
| Siblings | The two <product> elements |
Save XML files with the .xml extension and UTF-8 encoding. Then Urdu text, like a shop name in Urdu, works correctly too.
Viewing XML
Open an .xml file in Chrome, Edge or Firefox and the browser shows the tree with small arrows to open and close each part. VS Code also colours XML nicely.
Exercise
Exercise
How many root elements can an XML document have?
