Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 39 ยท XML, XPath and XSLT

XML Syntax and Structure

Learn XML from the start: elements, attributes, text, comments, CDATA, the declaration, well-formedness rules and the document tree, with a runnable mini parser.

XML (eXtensible Markup Language) describes data and documents with tags you invent yourself. It is older and wordier than JSON, yet it still powers RSS and Atom feeds, SVG images, Office files, Android layouts, SOAP services, sitemaps and countless enterprise systems. XML also handles things JSON does not: mixed text and markup, namespaces, comments and strict schema validation.

The Node runner has no built-in XML parser (browsers have DOMParser). The examples below use a ~25-line parser written for this course, a stand-in that handles elements, attributes, text, CDATA, comments and entities. It is not a validating parser and ignores DTDs. Use a real library (libxml2, Xerces, fast-xml-parser, lxml) in production.

A first document

XML
<?xml version="1.0" encoding="UTF-8"?>
<!-- A small library -->
<library>
  <book id="b1" lang="en">
    <title>The Little Compiler</title>
    <author>Ada Reyes</author>
    <price currency="USD">29.90</price>
  </book>
  <book id="b2" lang="es">
    <title>Sistemas de tipos</title>
    <author>Marta Gil</author>
    <price currency="EUR">35.00</price>
  </book>
</library>

Parts of an XML document:

  • XML declaration (<?xml ... ?>): optional, states the version and encoding. If present it must be first, with nothing before it.
  • Element: a start tag, content, and an end tag: <title>...</title>. Elements nest and form a tree.
  • Root element: exactly one element contains everything else (library).
  • Attribute: a name="value" pair inside a start tag (id="b1").
  • Text: the characters between tags.
  • Comment: <!-- ... -->.
  • Empty element: <br/>, short for <br></br>.

Well-formedness rules

A document is well-formed when it obeys these rules. A conforming parser must reject anything else; XML has no "forgiving" mode like HTML.

  1. Exactly one root element.
  2. Every start tag has a matching end tag, properly nested: <a><b></b></a>, never <a><b></a></b>.
  3. Tag names are case-sensitive: <Title> and <title> differ.
  4. Attribute values are always quoted (single or double), and an attribute name appears once per element.
  5. The characters < and & in text must be escaped as &lt; and &amp;.
  6. Names start with a letter or underscore and contain no spaces.

Parsing a document

Node.js Parse XML into a tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Attributes or elements?

Both can hold data: <price currency="USD">29.90</price> versus <price><currency>USD</currency><amount>29.90</amount></price>. A common guideline:

  • Use attributes for short metadata about the element: identifiers, languages, units.
  • Use elements for the content itself, anything that may repeat, have structure, or be long.

Attributes cannot contain child structure, cannot repeat, and have no order, so they are a poor fit for lists.

Character data, CDATA and entities

Five predefined entities exist: &lt; &gt; &amp; &quot; &apos;. For long blocks of text full of < and & (code samples, say), wrap it in a CDATA section, where nothing needs escaping except the closing ]]>.

Node.js Entities and CDATA

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Numeric character references also work: &#233; and &#xE9; both mean รฉ.

Whitespace and mixed content

Whitespace between elements is usually insignificant for data but part of the content for documents. Mixed content interleaves text and tags, as in <p>This is <b>bold</b> text.</p>, which is XML's home turf (XHTML, DocBook, DITA). JSON has no equivalent.

Common errors

Node.js What well-formedness errors look like

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many root elements may an XML document have?

    A well-formed document has a single root element containing everything else.
  2. 2. Are XML tag names case-sensitive?

    <Title> and <title> are different names in XML.
  3. 3. How do you write a literal ampersand in XML text?

    Use the predefined entity &, or wrap text in CDATA.
  4. 4. Which is a good use of an attribute?

    Attributes suit short metadata; structured or repeating data belongs in elements.

Summary

  • XML documents are trees of elements with attributes and text under one root.
  • Well-formedness is strict: matching, nested, case-sensitive tags and quoted attributes.
  • Escape < and &, or use CDATA for blocks of code.
  • Use attributes for small metadata, elements for content; mixed content is XML's special strength.

Next: Namespaces, entities and processing