Aral Code

Working with XML Lesson 6 of 9

Reading XML with JavaScript — DOMParser and fetch

Parse XML text with DOMParser, read elements and attributes with querySelector and getAttribute, display XML data as an HTML table, create XML with XMLSerializer, and load XML files with fetch.

Browsers have a built-in XML parser. With JavaScript, you can read an XML document, pull out the data, and show it on a web page, just like you work with HTML through the DOM.

DOMParser

Example Parsing XML and reading values
<pre id="out"></pre>
<script>
  const text = `<?xml version="1.0"?>
  <student lrn="136728140001">
    <name>Ana Reyes</name>
    <grade>10</grade>
    <subjects>
      <subject>Math</subject>
      <subject>Science</subject>
      <subject>ICT</subject>
    </subjects>
  </student>`;

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

  const lines = [
    "LRN: " + student.getAttribute("lrn"),
    "Name: " + doc.querySelector("name").textContent,
    "Grade: " + Number(doc.querySelector("grade").textContent),
    "Subjects: " + [...doc.querySelectorAll("subject")].map((s) => s.textContent).join(", "),
  ];
  document.getElementById("out").textContent = lines.join("\n");
</script>
  • parseFromString(text, "application/xml") turns text into an XML document.
  • querySelector and querySelectorAll work on XML just like on HTML.
  • textContent reads an element's text; getAttribute reads an attribute.
  • Everything read from XML is text, so convert numbers with Number().

XML data to an HTML table

Example Showing a product catalog
<style>
  table { border-collapse: collapse; font-family: sans-serif; }
  th, td { border: 1px solid #ccc; padding: 6px 10px; }
  th { background: #e3f1ec; }
  .out { color: crimson; }
</style>
<table id="t"><thead><tr><th>ID</th><th>Product</th><th>Price</th><th>Stock</th></tr></thead><tbody></tbody></table>
<p id="sum"></p>
<script>
  const xml = `<store>
    <product id="P01"><name>Pandesal</name><price>25</price><stock>40</stock></product>
    <product id="P02"><name>Kape</name><price>8</price><stock>200</stock></product>
    <product id="P03"><name>Chips</name><price>15</price><stock>0</stock></product>
  </store>`;
  const doc = new DOMParser().parseFromString(xml, "application/xml");
  const tbody = document.querySelector("#t tbody");
  let value = 0;

  doc.querySelectorAll("product").forEach((p) => {
    const price = Number(p.querySelector("price").textContent);
    const stock = Number(p.querySelector("stock").textContent);
    value += price * stock;
    const tr = document.createElement("tr");
    [p.getAttribute("id"), p.querySelector("name").textContent, "₱" + price, stock].forEach((v) => {
      const td = document.createElement("td");
      td.textContent = v;
      tr.append(td);
    });
    if (stock === 0) tr.className = "out";
    tbody.append(tr);
  });
  document.getElementById("sum").textContent = "Stock value: ₱" + value.toLocaleString("en-PH");
</script>

Detecting errors

If the XML isn't well-formed, DOMParser doesn't throw an error. Instead, the result contains a <parsererror> element. Always check:

const doc = new DOMParser().parseFromString(text, "application/xml");
if (doc.querySelector("parsererror")) {
  console.error("Invalid XML");
}

Creating XML

Example Building an XML document
<pre id="xml"></pre>
<script>
  const doc = document.implementation.createDocument("", "attendance", null);
  const root = doc.documentElement;
  root.setAttribute("date", "2026-12-02");

  [["Ana", "present"], ["Ben", "absent"], ["Carla", "late"]].forEach(([name, status]) => {
    const s = doc.createElement("student");
    s.setAttribute("status", status);
    s.textContent = name;
    root.append(s);
  });

  document.getElementById("xml").textContent = new XMLSerializer().serializeToString(doc);
</script>

XMLSerializer turns the document back into text, ready to save or send.

Loading an XML file

fetch("catalog.xml")
  .then((res) => res.text())
  .then((text) => {
    const doc = new DOMParser().parseFromString(text, "application/xml");
    console.log(doc.querySelectorAll("product").length + " products");
  });

This needs a web server (or a local one like php -S or VS Code's Live Server). Opening the HTML file directly with file:// usually blocks fetch.

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. Which object parses XML text in the browser?
2. How do you read the lrn attribute of an element s?
3. How does DOMParser report invalid XML?
4. What does XMLSerializer do?

By Sir Reyel · Last updated 2026-12-04