XML·XML from well-formed documents to XSLT

Parsing XML

Parse safely in JavaScript and Python without enabling external entities.

Beginner 14 min read Lesson 7 of 300 Challenge included
What you will be able to do
  • Never parse untrusted XML with a permissive parser.
  • Disable external entities and DTDs.
  • Check parse errors explicitly.
  • Prefer a schema at the boundary.

In plain English

XML parsers can be attacked with entity expansion or external entity resolution. Disable DTD processing and external entities for untrusted input. In browsers, DOMParser handles XML; in Python, use xml.etree.ElementTree with care.

parse.jsJavaScript
const parser = new DOMParser()
const doc = parser.parseFromString('<course><title>CSS</title></course>', 'application/xml')
if (doc.querySelector('parsererror')) throw new Error('Invalid XML')
console.log(doc.querySelector('title').textContent)
Your turn

Detect a parse error

Medium

Check for a parsererror element after parsing XML in the browser.

JAVASCRIPT · starter
const doc = new DOMParser().parseFromString(xml, 'application/xml')
Check your understanding before moving on.
Knowledge checkQuestion 1

Which attack targets XML entity expansion?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: RSS and Atom
Lesson 7 of 300 · 0% of course