XML Tutorial menu

Reading XML with Code

To use XML data, a program parses it: it reads the text and turns it into a tree of objects you can work with.

What is a Parser?

A parser reads XML text, checks that it is well-formed, and builds a tree in memory (the DOM, Document Object Model). Every major language has one built in.

LanguageBuilt-in tool
JavaScript (browser)DOMParser
Pythonxml.etree.ElementTree
PHPSimpleXML
C#System.Xml.Linq (XDocument)
Javajavax.xml.parsers

JavaScript: DOMParser

Example

javascript
const text = `
<shop>
  <product><name>Galaxy A15</name><price>42000</price></product>
  <product><name>Fast Charger</name><price>2500</price></product>
</shop>`;

const doc = new DOMParser().parseFromString(text, "application/xml");

if (doc.querySelector("parsererror")) {
  console.log("The XML is not well-formed.");
} else {
  for (const p of doc.querySelectorAll("product")) {
    const name = p.querySelector("name").textContent;
    const price = Number(p.querySelector("price").textContent);
    console.log(`${name}: Rs ${price.toLocaleString("en-PK")}`);
  }
}
Output
Galaxy A15: Rs 42,000
Fast Charger: Rs 2,500

If the XML is broken, DOMParser does not throw an error. Instead, the result contains a <parsererror> element, so always check for it.

To load an XML file from a server, use fetch():

Example

javascript
const res = await fetch("/sitemap.xml");
const xml = new DOMParser().parseFromString(await res.text(), "application/xml");
console.log(xml.getElementsByTagName("loc").length + " pages in the sitemap");

Python: ElementTree

Example

python
import xml.etree.ElementTree as ET

text = """
<students>
  <student id="S01"><name>Ali Raza</name><marks>78</marks></student>
  <student id="S02"><name>Ayesha Khan</name><marks>91</marks></student>
  <student id="S03"><name>Bilal Ahmed</name><marks>55</marks></student>
</students>
"""

root = ET.fromstring(text)

for s in root.findall("student"):
    name = s.find("name").text
    marks = int(s.find("marks").text)
    print(s.get("id"), name, "Pass" if marks >= 60 else "Needs practice")

top = max(root.findall("student"), key=lambda s: int(s.find("marks").text))
print("Top student:", top.find("name").text)
Output
S01 Ali Raza Pass
S02 Ayesha Khan Pass
S03 Bilal Ahmed Needs practice
Top student: Ayesha Khan

For a file, use ET.parse("students.xml").getroot(). ElementTree also supports simple XPath, like root.findall(".//student[@id='S02']").

Creating XML with Python

Example

python
import xml.etree.ElementTree as ET

order = ET.Element("order", id="1045")
ET.SubElement(order, "customer").text = "Sana"
ET.SubElement(order, "total", currency="PKR").text = "3200"

ET.indent(order)
print(ET.tostring(order, encoding="unicode"))
Output
<order id="1045">
  <customer>Sana</customer>
  <total currency="PKR">3200</total>
</order>

Always build XML with a library like this instead of joining strings. The library escapes characters like & and < for you, so the result is always well-formed.

Real Uses: RSS and Sitemaps

An RSS feed lists the latest posts of a blog or news site. Apps and readers check it for new content:

Example

xml
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <title>Workownix Blog</title>
    <link>https://example.com/blog</link>
    <item>
      <title>5 Tips for New Freelancers</title>
      <link>https://example.com/blog/freelance-tips</link>
      <pubDate>Thu, 15 Oct 2026 09:00:00 +0500</pubDate>
    </item>
  </channel>
</rss>

A sitemap (/sitemap.xml) tells search engines which pages your website has, as you saw in the namespaces lesson. Submitting it in Google Search Console helps your pages get found.

XML vs JSON

XMLJSON
Looks likeTagsCurly braces and keys
SizeLargerSmaller
Attributes and namespacesYesNo
Schemas and validationStrong (XSD)JSON Schema
Common inDocuments, feeds, enterprise systems, office filesWeb and mobile APIs

Most new web APIs use JSON, but XML is still the standard for sitemaps, RSS, SVG, office documents and many banking and government systems.

Exercise

Exercise

In Python's ElementTree, which method gets the value of an attribute?

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