XML Exercises
Time to practise. Each task has a starter playground: edit it, press ▶ Run (or Ctrl+Enter), and only open the solution after a real attempt. For the XML tasks, success means the parser reports Well-formed XML with the tree you intended. For the JavaScript tasks, compare your console output with the expected result given in the task.
| # | Topic |
|---|---|
| 1 | Fix syntax errors |
| 2 | Design a document |
| 3 | Escaping and CDATA |
| 4 | Namespaces |
| 5 | Read values with the DOM |
| 6 | XPath queries |
| 7 | Change and add nodes |
| 8 | Build and serialise a document |
Exercise 1 — Fix the syntax errors
This document has four well-formedness errors. Fix them all so the parser accepts it. Run after each fix — the parser only reports the first problem it meets.
<playlist name=Road trip>
<song>
<title>Fast Car</Title>
<artist>Tracy Chapman</artist>
<song>
<title>Running Up That Hill</title>
<artist>Kate Bush</artist>
</song>
</playlist>
<playlist name="Chill"/>Show solution
name=Road trip→ the value must be quoted:name="Road trip".</Title>→ case must match:</title>.- The first
<song>is never closed — add</song>. - Two root elements — wrap both playlists in one root (or delete the second).
<playlists>
<playlist name="Road trip">
<song>
<title>Fast Car</title>
<artist>Tracy Chapman</artist>
</song>
<song>
<title>Running Up That Hill</title>
<artist>Kate Bush</artist>
</song>
</playlist>
<playlist name="Chill"/>
</playlists>Exercise 2 — Design a document
Write an XML document for a cinema schedule: one cinema called "Lumière" with two films. Each film has a title, a duration in minutes, an age rating, and one or more showtimes. Use at least one attribute and at least one repeated element.
<!-- write your cinema schedule here -->
<cinema>
</cinema>Show solution
One possible design — attributes for short metadata, elements for repeatable data:
<cinema name="Lumière">
<film rating="12">
<title>The Night Orchard</title>
<duration unit="min">118</duration>
<showtime>2026-11-06T18:30</showtime>
<showtime>2026-11-06T21:15</showtime>
</film>
<film rating="U">
<title>Paper Boats</title>
<duration unit="min">94</duration>
<showtime>2026-11-07T14:00</showtime>
</film>
</cinema>Exercise 3 — Escaping and CDATA
Make this document well-formed without changing the text the reader sees. Use entities for the <step> and a CDATA section for the <code> block.
<tip>
<step>Check that width < 600 & height < 400</step>
<code>
if (w < 600 && h < 400) { show("<small>"); }
</code>
</tip>Show solution
<tip>
<step>Check that width < 600 & height < 400</step>
<code><![CDATA[
if (w < 600 && h < 400) { show("<small>"); }
]]></code>
</tip>Exercise 4 — Namespaces
The document mixes a recipe vocabulary with a nutrition vocabulary, but the prefixes are not declared. Declare r as https://example.com/recipe and n as https://example.com/nutrition so it becomes well-formed.
<r:recipe>
<r:name>Lentil soup</r:name>
<n:calories per="serving">310</n:calories>
<n:protein unit="g">18</n:protein>
</r:recipe>Show solution
<r:recipe xmlns:r="https://example.com/recipe"
xmlns:n="https://example.com/nutrition">
<r:name>Lentil soup</r:name>
<n:calories per="serving">310</n:calories>
<n:protein unit="g">18</n:protein>
</r:recipe>Exercise 5 — Read values with the DOM
Print each planet's name and its number of moons, then the total number of moons. Expected output:
Mercury: 0
Earth: 1
Mars: 2
Total moons: 3<!DOCTYPE html>
<html>
<body>
<script>
const xml = `<planets>
<planet name="Mercury"><moons>0</moons></planet>
<planet name="Earth"><moons>1</moons></planet>
<planet name="Mars"><moons>2</moons></planet>
</planets>`;
const doc = new DOMParser().parseFromString(xml, 'application/xml');
// your code here
</script>
</body>
</html>Show solution
let total = 0;
for (const p of doc.querySelectorAll('planet')) {
const moons = Number(p.querySelector('moons').textContent);
console.log(`${p.getAttribute('name')}: ${moons}`);
total += moons;
}
console.log('Total moons:', total);Exercise 6 — XPath queries
Fill in the three XPath expressions so the output is:
Cheap: Pencil, Eraser
Second item: Ruler
Count: 4<!DOCTYPE html>
<html>
<body>
<script>
const xml = `<stationery>
<item price="0.80">Pencil</item>
<item price="2.50">Ruler</item>
<item price="0.60">Eraser</item>
<item price="4.90">Stapler</item>
</stationery>`;
const doc = new DOMParser().parseFromString(xml, 'application/xml');
const nodes = (xp) => {
const r = doc.evaluate(xp, doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
return Array.from({ length: r.snapshotLength }, (_, i) => r.snapshotItem(i).textContent);
};
const num = (xp) => doc.evaluate(xp, doc, null, XPathResult.NUMBER_TYPE, null).numberValue;
// TODO: replace each placeholder XPath ('/nothing-yet') with a real expression.
console.log('Cheap:', nodes('/nothing-yet').join(', ')); // items cheaper than 1
console.log('Second item:', nodes('/nothing-yet')[0]); // the second item
console.log('Count:', num('count(/nothing-yet)')); // count the items
</script>
</body>
</html>Show solution
console.log('Cheap:', nodes('//item[@price < 1]').join(', '));
console.log('Second item:', nodes('/stationery/item[2]')[0]);
console.log('Count:', num('count(//item)'));Remember that XPath positions start at 1.
Exercise 7 — Change and add nodes
Using the DOM: (a) mark the task "Buy milk" as done by setting its done attribute to yes, (b) remove the task "Old reminder", and (c) add a new task "Call plumber" with done="no" at the end. Expected output:
<todo><task done="yes">Buy milk</task><task done="no">Write report</task><task done="no">Call plumber</task></todo><!DOCTYPE html>
<html>
<body>
<script>
const doc = new DOMParser().parseFromString(
'<todo><task done="no">Buy milk</task><task done="no">Old reminder</task><task done="no">Write report</task></todo>',
'application/xml');
const find = (text) => [...doc.querySelectorAll('task')].find(t => t.textContent === text);
// your code here
console.log(new XMLSerializer().serializeToString(doc));
</script>
</body>
</html>Show solution
find('Buy milk').setAttribute('done', 'yes');
find('Old reminder').remove();
const task = doc.createElement('task');
task.setAttribute('done', 'no');
task.textContent = 'Call plumber';
doc.documentElement.appendChild(task);Exercise 8 — Build and serialise a document
Turn the scores array into XML and print it. Expected output:
<results game="quiz"><player rank="1" name="Zoe">42</player><player rank="2" name="Ravi">37</player><player rank="3" name="Lin">35</player></results><!DOCTYPE html>
<html>
<body>
<script>
const scores = [['Ravi', 37], ['Lin', 35], ['Zoe', 42]];
// 1. sort by score (highest first)
// 2. create a document with root <results game="quiz">
// 3. add one <player rank=".." name="..">score</player> per entry
// 4. print it with XMLSerializer
</script>
</body>
</html>Show solution
const sorted = [...scores].sort((a, b) => b[1] - a[1]);
const doc = document.implementation.createDocument(null, 'results');
doc.documentElement.setAttribute('game', 'quiz');
sorted.forEach(([name, score], i) => {
const p = doc.createElement('player');
p.setAttribute('rank', i + 1);
p.setAttribute('name', name);
p.textContent = score;
doc.documentElement.appendChild(p);
});
console.log(new XMLSerializer().serializeToString(doc));Test yourself
A parser reports only one error, but your file has four. Why?
- The others aren't errors
- XML parsers stop at the first fatal error
- Only attribute errors are reported
- The playground hides them
Which XPath selects items whose price attribute is below 1?
//item[price < 1]//item[@price < 1]//item/@price < 1//@item[price < 1]