TExcelTAD
Home › XML › XML Mini Project

XML Mini Project: Book Catalog Viewer

In this project you'll build a small book catalog viewer that runs entirely in the browser. It loads XML data, checks it, shows it as a table, lets the user filter and sort, adds new books, and exports the updated catalog as XML. Each step reuses skills from the course; each playground is complete, so you can run any step on its own.

Step Skill
1. Design the data Elements, attributes, well-formedness
2. Parse and check DOMParser, parsererror, simple validation
3. Display a table DOM navigation, getting values
4. Filter, search and sort XPath, arrays
5. Add books and export Creating nodes, XMLSerializer

Step 1 — Design the data

Every book gets an id and a genre as attributes (short metadata) and child elements for the real data. Prices carry a currency attribute.

xml · try it yourself
<?xml version="1.0" encoding="UTF-8"?>
<catalog updated="2026-10-01">
  <book id="bk101" genre="fantasy">
    <title>The Left Hand of Darkness</title>
    <author>Ursula K. Le Guin</author>
    <year>1969</year>
    <price currency="EUR">9.90</price>
  </book>
  <book id="bk102" genre="mystery">
    <title>The Murder of Roger Ackroyd</title>
    <author>Agatha Christie</author>
    <year>1926</year>
    <price currency="EUR">7.50</price>
  </book>
  <book id="bk103" genre="science">
    <title>The Gene</title>
    <author>Siddhartha Mukherjee</author>
    <year>2016</year>
    <price currency="EUR">14.20</price>
  </book>
  <book id="bk104" genre="fantasy">
    <title>Piranesi</title>
    <author>Susanna Clarke</author>
    <year>2020</year>
    <price currency="EUR">11.00</price>
  </book>
  <book id="bk105" genre="mystery">
    <title>The Big Sleep</title>
    <author>Raymond Chandler</author>
    <year>1939</year>
    <price currency="EUR">8.25</price>
  </book>
</catalog>

Tip: Before writing code, sketch the rules a valid catalog must follow: every book needs a unique id, a title, an author, a numeric year and a numeric price. Step 2 checks exactly those.

Step 2 — Parse and check

A loader function parses the text, rejects broken XML, and collects rule violations. One book below is deliberately bad.

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xml = `<catalog>
      <book id="bk101" genre="fantasy"><title>The Left Hand of Darkness</title><author>Ursula K. Le Guin</author><year>1969</year><price currency="EUR">9.90</price></book>
      <book id="bk102" genre="mystery"><title>The Murder of Roger Ackroyd</title><author>Agatha Christie</author><year>1926</year><price currency="EUR">7.50</price></book>
      <book id="bk102" genre="science"><title>The Gene</title><year>twenty-sixteen</year><price currency="EUR">14.20</price></book>
    </catalog>`;

    function loadCatalog(text) {
      const doc = new DOMParser().parseFromString(text, 'application/xml');
      if (doc.querySelector('parsererror')) return { doc: null, errors: ['The file is not well-formed XML.'] };

      const errors = [];
      const ids = new Set();
      doc.querySelectorAll('book').forEach((b, i) => {
        const where = `book ${i + 1}`;
        const id = b.getAttribute('id');
        if (!id) errors.push(`${where}: missing id`);
        else if (ids.has(id)) errors.push(`${where}: duplicate id ${id}`);
        ids.add(id);
        for (const field of ['title', 'author', 'year', 'price']) {
          if (!b.querySelector(field)) errors.push(`${where}: missing <${field}>`);
        }
        for (const field of ['year', 'price']) {
          const el = b.querySelector(field);
          if (el && Number.isNaN(Number(el.textContent))) errors.push(`${where}: <${field}> is not a number`);
        }
      });
      return { doc, errors };
    }

    const { doc, errors } = loadCatalog(xml);
    console.log(`Books: ${doc.querySelectorAll('book').length}, problems: ${errors.length}`);
    errors.forEach(e => console.log(' -', e));
  </script>
</body>
</html>

Fix the third book (unique id, add an <author>, 2016 as the year) and run again to see problems: 0.

Step 3 — Display a table

Convert the XML into an array of plain objects once, then render HTML from that array. Keeping a toBooks() step separates "reading XML" from "showing data".

html · try it yourself
<!DOCTYPE html>
<html>
<head>
<style>
  body { font-family: system-ui, sans-serif; }
  table { border-collapse: collapse; width: 100%; }
  th, td { padding: 6px 10px; border-bottom: 1px solid #ddd; text-align: left; }
  th { background: #0060ac; color: #fff; }
  td.num { text-align: right; }
  .tag { font-size: .8em; padding: 2px 6px; border-radius: 8px; background: #e3f0fb; }
</style>
</head>
<body>
  <table>
    <thead><tr><th>Title</th><th>Author</th><th>Genre</th><th>Year</th><th>Price</th></tr></thead>
    <tbody id="rows"></tbody>
  </table>
  <script>
    const xml = `<catalog>
      <book id="bk101" genre="fantasy"><title>The Left Hand of Darkness</title><author>Ursula K. Le Guin</author><year>1969</year><price currency="EUR">9.90</price></book>
      <book id="bk102" genre="mystery"><title>The Murder of Roger Ackroyd</title><author>Agatha Christie</author><year>1926</year><price currency="EUR">7.50</price></book>
      <book id="bk103" genre="science"><title>The Gene</title><author>Siddhartha Mukherjee</author><year>2016</year><price currency="EUR">14.20</price></book>
      <book id="bk104" genre="fantasy"><title>Piranesi</title><author>Susanna Clarke</author><year>2020</year><price currency="EUR">11.00</price></book>
      <book id="bk105" genre="mystery"><title>The Big Sleep</title><author>Raymond Chandler</author><year>1939</year><price currency="EUR">8.25</price></book>
    </catalog>`;
    const doc = new DOMParser().parseFromString(xml, 'application/xml');

    function toBooks(doc) {
      const text = (b, sel) => b.querySelector(sel).textContent;
      return [...doc.querySelectorAll('book')].map(b => ({
        id: b.getAttribute('id'),
        genre: b.getAttribute('genre'),
        title: text(b, 'title'),
        author: text(b, 'author'),
        year: Number(text(b, 'year')),
        price: Number(text(b, 'price')),
      }));
    }

    function render(books) {
      const tbody = document.getElementById('rows');
      tbody.replaceChildren();
      for (const b of books) {
        const tr = tbody.insertRow();
        tr.insertCell().textContent = b.title;
        tr.insertCell().textContent = b.author;
        const g = document.createElement('span');
        g.className = 'tag'; g.textContent = b.genre;
        tr.insertCell().append(g);
        const y = tr.insertCell(); y.textContent = b.year; y.className = 'num';
        const p = tr.insertCell(); p.textContent = '€' + b.price.toFixed(2); p.className = 'num';
      }
    }

    const books = toBooks(doc);
    render(books);
    console.log(`Rendered ${books.length} books`);
  </script>
</body>
</html>

Step 4 — Filter, search and sort

Now add controls. The genre list is built from the data itself with XPath (so new genres appear automatically), and filtering uses an XPath expression built from the selected genre.

html · try it yourself
<!DOCTYPE html>
<html>
<head>
<style>
  body { font-family: system-ui, sans-serif; }
  .bar { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 8px; }
  table { border-collapse: collapse; width: 100%; }
  th, td { padding: 6px 10px; border-bottom: 1px solid #ddd; text-align: left; }
  th { background: #0060ac; color: #fff; cursor: pointer; }
  td.num { text-align: right; }
</style>
</head>
<body>
  <div class="bar">
    <select id="genre"><option value="">All genres</option></select>
    <input id="q" placeholder="Search title or author">
  </div>
  <table>
    <thead><tr><th data-key="title">Title</th><th data-key="author">Author</th><th data-key="year">Year ▲▼</th><th data-key="price">Price ▲▼</th></tr></thead>
    <tbody id="rows"></tbody>
  </table>
  <p id="status"></p>
  <script>
    const xml = `<catalog>
      <book id="bk101" genre="fantasy"><title>The Left Hand of Darkness</title><author>Ursula K. Le Guin</author><year>1969</year><price>9.90</price></book>
      <book id="bk102" genre="mystery"><title>The Murder of Roger Ackroyd</title><author>Agatha Christie</author><year>1926</year><price>7.50</price></book>
      <book id="bk103" genre="science"><title>The Gene</title><author>Siddhartha Mukherjee</author><year>2016</year><price>14.20</price></book>
      <book id="bk104" genre="fantasy"><title>Piranesi</title><author>Susanna Clarke</author><year>2020</year><price>11.00</price></book>
      <book id="bk105" genre="mystery"><title>The Big Sleep</title><author>Raymond Chandler</author><year>1939</year><price>8.25</price></book>
    </catalog>`;
    const doc = new DOMParser().parseFromString(xml, 'application/xml');

    function xpathNodes(expr) {
      const r = doc.evaluate(expr, doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
      return Array.from({ length: r.snapshotLength }, (_, i) => r.snapshotItem(i));
    }
    const toBook = (b) => ({
      title: b.querySelector('title').textContent,
      author: b.querySelector('author').textContent,
      year: Number(b.querySelector('year').textContent),
      price: Number(b.querySelector('price').textContent),
    });

    // Distinct genres, straight from the data
    const genres = [...new Set(xpathNodes('//book/@genre').map(a => a.value))].sort();
    for (const g of genres) document.getElementById('genre').add(new Option(g, g));

    let sortKey = 'title', ascending = true;

    function update() {
      const genre = document.getElementById('genre').value;
      const q = document.getElementById('q').value.trim().toLowerCase();
      const expr = genre ? `//book[@genre='${genre}']` : '//book';   // genre comes from our own list
      const books = xpathNodes(expr).map(toBook)
        .filter(b => !q || b.title.toLowerCase().includes(q) || b.author.toLowerCase().includes(q))
        .sort((a, b) => (a[sortKey] > b[sortKey] ? 1 : a[sortKey] < b[sortKey] ? -1 : 0) * (ascending ? 1 : -1));

      const tbody = document.getElementById('rows');
      tbody.replaceChildren();
      for (const b of books) {
        const tr = tbody.insertRow();
        tr.insertCell().textContent = b.title;
        tr.insertCell().textContent = b.author;
        Object.assign(tr.insertCell(), { textContent: b.year, className: 'num' });
        Object.assign(tr.insertCell(), { textContent: '€' + b.price.toFixed(2), className: 'num' });
      }
      document.getElementById('status').textContent =
        `${books.length} book(s), total €${books.reduce((s, b) => s + b.price, 0).toFixed(2)}`;
    }

    document.getElementById('genre').addEventListener('change', update);
    document.getElementById('q').addEventListener('input', update);
    document.querySelectorAll('th').forEach(th => th.addEventListener('click', () => {
      const key = th.dataset.key;
      ascending = key === sortKey ? !ascending : true;
      sortKey = key;
      update();
    }));
    update();
    console.log('Genres found:', genres.join(', '));
  </script>
</body>
</html>

Try it: pick a genre, type "the" in the search box, and click the column headers to sort.

Note: Building XPath from user-typed text is risky (a quote would break the expression). Here the genre comes from a list we generated ourselves; the free-text search is done in JavaScript instead.

Step 5 — Add books and export XML

The final version edits the XML document itself: the form creates a new <book> element, the table re-renders from the DOM, and the Export button serialises the catalog.

html · try it yourself
<!DOCTYPE html>
<html>
<head>
<style>
  body { font-family: system-ui, sans-serif; }
  form { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px; }
  input, select { padding: 4px; }
  input[name=title], input[name=author] { flex: 1 1 140px; }
  input[name=year], input[name=price] { width: 80px; }
  table { border-collapse: collapse; width: 100%; }
  th, td { padding: 5px 8px; border-bottom: 1px solid #ddd; text-align: left; }
  th { background: #0060ac; color: #fff; }
  pre { background: #f4f6f8; padding: 8px; overflow: auto; font-size: 12px; }
</style>
</head>
<body>
  <form id="add">
    <input name="title" placeholder="Title" required>
    <input name="author" placeholder="Author" required>
    <select name="genre"><option>fantasy</option><option>mystery</option><option>science</option></select>
    <input name="year" type="number" placeholder="Year" required>
    <input name="price" type="number" step="0.01" placeholder="Price" required>
    <button>Add book</button>
  </form>
  <table><thead><tr><th>Id</th><th>Title</th><th>Author</th><th>Year</th><th>Price</th><th></th></tr></thead><tbody id="rows"></tbody></table>
  <p><button id="export">Export XML</button></p>
  <pre id="xmlOut"></pre>
  <script>
    const doc = new DOMParser().parseFromString(`<catalog>
      <book id="bk101" genre="fantasy"><title>The Left Hand of Darkness</title><author>Ursula K. Le Guin</author><year>1969</year><price currency="EUR">9.90</price></book>
      <book id="bk102" genre="mystery"><title>The Murder of Roger Ackroyd</title><author>Agatha Christie</author><year>1926</year><price currency="EUR">7.50</price></book>
    </catalog>`, 'application/xml');
    const catalog = doc.documentElement;

    function child(parent, name, text, attrs = {}) {
      const el = doc.createElement(name);
      for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v);
      el.textContent = text;
      parent.appendChild(el);
      return el;
    }

    function nextId() {
      const nums = [...catalog.querySelectorAll('book')].map(b => Number(b.getAttribute('id').slice(2)));
      return 'bk' + (Math.max(100, ...nums) + 1);
    }

    function render() {
      const tbody = document.getElementById('rows');
      tbody.replaceChildren();
      for (const b of catalog.querySelectorAll('book')) {
        const tr = tbody.insertRow();
        for (const v of [b.getAttribute('id'), b.querySelector('title').textContent, b.querySelector('author').textContent,
                         b.querySelector('year').textContent, '€' + Number(b.querySelector('price').textContent).toFixed(2)]) {
          tr.insertCell().textContent = v;
        }
        const del = document.createElement('button');
        del.textContent = '✕';
        del.title = 'Remove';
        del.onclick = () => { b.remove(); render(); };   // removes the <book> from the XML DOM
        tr.insertCell().append(del);
      }
    }

    document.getElementById('add').addEventListener('submit', (e) => {
      e.preventDefault();
      const f = new FormData(e.target);
      const book = doc.createElement('book');
      book.setAttribute('id', nextId());
      book.setAttribute('genre', f.get('genre'));
      child(book, 'title', f.get('title'));
      child(book, 'author', f.get('author'));
      child(book, 'year', f.get('year'));
      child(book, 'price', Number(f.get('price')).toFixed(2), { currency: 'EUR' });
      catalog.appendChild(book);
      e.target.reset();
      render();
      console.log('Added', book.getAttribute('id'));
    });

    document.getElementById('export').addEventListener('click', () => {
      catalog.setAttribute('updated', '2026-10-16');
      const text = '<?xml version="1.0" encoding="UTF-8"?>\n' + new XMLSerializer().serializeToString(doc);
      document.getElementById('xmlOut').textContent = text;
    });

    render();
    console.log('Catalog has', catalog.querySelectorAll('book').length, 'books. Add one, then press Export XML.');
  </script>
</body>
</html>

Add a book with an ampersand in the title, such as Pride & Prejudice, and export: the serializer writes &amp; for you, so the exported file is always well-formed.

Ideas to extend the project

  1. Add an Edit button that loads a book into the form and updates its elements with textContent / setAttribute.
  2. Offer the export as a real download with a Blob and an <a download> link (see the Serializing lesson).
  3. Let the user paste their own catalog XML into a <textarea>, run loadCatalog from Step 2, and show the problems list if it fails.
  4. Generate an RSS feed of the five newest books, or an SVG bar chart of books per genre.

Test yourself

Why does Step 3 convert the XML into an array of plain objects before rendering?

  1. Browsers can't display XML
  2. It separates reading the XML from displaying the data, so the rendering code doesn't depend on the DOM structure
  3. Arrays use less memory than XML
  4. XMLSerializer requires it

In Step 5, what happens when the ✕ button calls b.remove()?

  1. Only the table row disappears
  2. The <book> element is removed from the XML document, and the table is re-rendered from it
  3. The original file on disk is changed
  4. Nothing until Export is pressed

Why is the free-text search done in JavaScript rather than by inserting the text into an XPath expression?

  1. XPath can't compare strings
  2. User text containing a quote could break or alter the XPath expression
  3. JavaScript is always faster
  4. XPath is case-sensitive