HTML versus XML: Parsing and Namespaces
The media type selects parsing rules
HTML served as text/html uses the HTML parser even if it looks like XHTML. XML parsing is selected for XML media types, such as application/xhtml+xml. DOMParser lets us compare the modes locally without HTTP. XML is case-sensitive and requires well-formed nesting.
<output id="result"></output><script> const parser = new DOMParser(); const html = parser.parseFromString("<P>Hi</P>", "text/html"); const xml = parser.parseFromString("<P>Hi</P>", "application/xml"); const result = html.querySelector("p").localName + " / " + xml.documentElement.localName; document.querySelector("#result").textContent = String(result);</script>Expected output: p / P
Well-formed XML versus recovery
The deliberately malformed XML below has overlapping tags. DOMParser returns a document with parsererror information rather than repairing the nesting as HTML does. A well-formed XML document is not automatically valid against a schema or conforming XHTML.
<output id="result"></output><script> const parser = new DOMParser(); const bad = parser.parseFromString("<root><item></root>", "application/xml"); const good = parser.parseFromString("<root><item/></root>", "application/xml"); const result = Boolean(bad.querySelector("parsererror")) + " / " + good.documentElement.firstElementChild.localName; document.querySelector("#result").textContent = String(result);</script>Expected output: true / item
Namespaces identify element vocabularies
HTML parsing assigns namespaces automatically when it enters SVG or MathML content. XML requires namespace declarations for namespaced vocabularies. XHTML uses the HTML namespace http://www.w3.org/1999/xhtml; the namespace is an identifier, not a fetch instruction.
<output id="result"></output><script> const parsed = new DOMParser().parseFromString("<p>Text</p><svg><circle/></svg><math><mi>x</mi></math>", "text/html"); const result = ["p", "circle", "mi"].map(s => parsed.querySelector(s).namespaceURI).join(" | "); document.querySelector("#result").textContent = String(result);</script>Expected output: http://www.w3.org/1999/xhtml | http://www.w3.org/2000/svg | http://www.w3.org/1998/Math/MathML
Common mistakes and practice
Do not assume a filename extension or trailing slash switches parser modes. Inspect HTTP Content-Type in deployment and document.contentType in the browser. XML has stricter syntax but that does not make arbitrary XML safe to insert into a live page.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTML versus XML: Parsing and Namespaces — Knowledge Check
Apply the internals concepts taught in this lesson.
Which MIME type selects HTML parsing?
Is XML case-sensitive for element names?
How does DOMParser expose malformed XML?
What is a namespace URI used for?
Does well-formed XML imply schema validity?