Programming Search⌘K

Conceptcore

Tree, event and pull parsers

Also called DOM, SAX, StAX, push parser, streaming parser.

A tree parser loads a whole document into memory. An event parser calls the program for each part, and a pull parser gives the next part when the program asks.

Idea

A parser reads the text of a document and gives its structure to the program. There are three ways to give it. A tree parser reads the whole document and returns a tree of nodes. An event parser, also called a push parser, calls a function of the program for each part of the document as it reads. A pull parser gives the parts one at a time, when the program asks for the next one. The three models are most visible in XML, where each one has a standard API: DOM for trees, SAX for events and StAX for pull parsing in Java. The same models exist for JSON and for other formats.

The SAX project describes the first two. A tree-based API maps "an XML document into an internal tree structure, then allow an application to navigate that tree." An event-based API "reports parsing events (such as the start and end of elements) directly to the application through callbacks, and does not usually build an internal tree."1 The pull model turns the event model around. "The XMLStreamReader is designed to iterate over XML using next() and hasNext()."2

The choice is a trade between convenience and memory. A tree is easy to use: the program can go to any node, at any time, in any order. But the tree must fit in memory, and it has an object for each node, so it takes more memory than the text. A stream of events or tokens needs only a small, fixed amount of memory, but the program sees each part only once, in document order.

How it works

The document below has three orders. Each model below adds the totals.

<orders>
  <order id="1"><total>9.50</total></order>
  <order id="2"><total>20.00</total></order>
  <order id="3"><total>4.25</total></order>
</orders>

Tree. The parser reads all of the text and builds a node for each element, attribute and piece of text. The program then walks the tree or searches it, for example with XPath. In Python, ElementTree.fromstring returns the root element. In Java, DocumentBuilder.parse returns a DOM Document. The program can change the tree and write it back.

Event (push). The program gives the parser a handler object. The parser reads the text and calls the methods of the handler: one call for each start tag, each piece of text and each end tag. The parser controls the loop, and the program sees one event at a time. To know where it is, the handler must keep its own state, such as the name of the current element or a stack of the open elements. The trace below shows the events of SAX for a small document.

import xml.sax


class Trace(xml.sax.ContentHandler):
    def startElement(self, name, attrs):
        print("start", name, dict(attrs))

    def characters(self, content):
        print("text ", repr(content))

    def endElement(self, name):
        print("end  ", name)


xml.sax.parseString(b'<order id="1">Tea &amp; cake<total>9.50</total></order>', Trace())
Output
start order {'id': '1'}
text  'Tea '
text  '&'
text  ' cake'
start total {}
text  '9.50'
end   total
end   order

The text Tea &amp; cake comes in three pieces. This is permitted: "SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks".3 A handler must join the pieces before it uses the text.

Pull. The program owns the loop. It asks the parser for the next event or token, looks at it and decides what to do. The state can be in the local variables and the call stack of the program, as in a recursive descent parser. The program can also stop early, skip a subtree or give the reader to a function that reads one record. The Java documentation says that StAX "is designed to be the lowest level and most efficient way to read XML data."2 The .NET documentation says: "XmlReader uses a pull model to retrieve data."4

A pull parser can also take its input in pieces, from a network socket for example. The Python XMLPullParser "does not require a blocking read to obtain the XML data, and is instead fed with data incrementally with XMLPullParser.feed() calls."5

import xml.etree.ElementTree as ET

parser = ET.XMLPullParser(events=("start", "end"))
for chunk in ['<orders><order id="1">', '<total>9.50</to', 'tal></order></orders>']:
    parser.feed(chunk)
    for event, element in parser.read_events():
        print(repr(chunk), event, element.tag)
parser.close()
Output
'<orders><order id="1">' start orders
'<orders><order id="1">' start order
'<total>9.50</to' start total
'tal></order></orders>' end total
'tal></order></orders>' end order
'tal></order></orders>' end orders

The end tag </total> is split between two pieces, and the parser reports the end of total only when it has the whole tag.

Mixed. Many programs use a pull parser to find each record and a tree for the record itself. The program moves to the start of each order, reads only that element as a small tree, uses it and drops it. In Go, Decoder.Token moves forward and DecodeElement reads one element into a struct.6 In .NET, XNode.ReadFrom reads the element at the position of an XmlReader. In Python, iterparse builds the elements and the program clears each one after use. The example files show this pattern.

In languages

LanguageVerdictNote
PythonStandard library
C++LibraryThe C++ standard library has no XML parser. Alternative: Pugixml and TinyXML-2 build trees; the C libraries Expat and libxml2 give events and pull reading.
JavaStandard library
CLibraryISO C has no XML functions. Alternative: Expat is an event parser; libxml2 has a tree, a SAX interface and the pull reader xmlTextReader.
C#Standard library
JavaScriptLibraryBrowsers have the tree parser DOMParser, and Node.js has no built-in XML parser; JSON.parse builds a tree of values. Alternative: The packages sax or saxes for events, and @xmldom/xmldom for a tree.
TypeScriptLibraryTypeScript has the same runtime as JavaScript; Node.js has no built-in XML parser. Alternative: The packages sax or saxes for events, and @xmldom/xmldom for a tree.
GoStandard library
RustLibraryThe Rust standard library has no XML parser. Alternative: Quick-xml is a pull parser, and roxmltree builds a read-only tree.
KotlinLibraryThe Kotlin standard library has no XML; on the JVM a program can use DOM, SAX and StAX of Java, as in the Java example. No example file exists because kotlinc is not installed. Alternative: The java.xml module of the Java platform.
SQLDoes not applyA database parses an XML value inside its own engine, and the query sees the result, not the parser model.
BashLibraryBash has no XML parser. Alternative: Xmlstarlet and xmllint load a tree; a program in another language can stream.
PowerShellStandard libraryThe [xml] type accelerator builds an XmlDocument tree, and [System.Xml.XmlReader]::Create gives the .NET pull parser; no example file because PowerShell is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup has no parser API; the browser builds a DOM tree of the page.
CSSDoes not applyStyle sheets have no parser API.
Regular expressionsDoes not applyA regular expression has no parser model for nested markup.
Language Tree Event (push) Pull
Python xml.etree.ElementTree, xml.dom.minidom xml.sax7 iterparse, XMLPullParser5
Java DOM, DocumentBuilder SAX, SAXParser StAX, XMLStreamReader2
C# XDocument, XmlDocument none in the base library XmlReader4
Go xml.Unmarshal into structs none Decoder.Token6
JavaScript DOMParser in browsers packages such as sax and saxes none built in
C libxml2 tree Expat, libxml2 SAX libxml2 xmlTextReader

For JSON, the same models exist. json.loads and JSON.parse build a tree of values. Streaming JSON parsers give events or tokens, such as the Jackson JsonParser in Java and Utf8JsonReader in .NET (see Stream-parse a large JSON file).

PythonGitHub
import io
import xml.sax
import xml.etree.ElementTree as ET

text = b"""<orders>
  <order id="1"><total>9.50</total></order>
  <order id="2"><total>20.00</total></order>
  <order id="3"><total>4.25</total></order>
</orders>"""

# Tree: parse the whole document, then walk it.
root = ET.fromstring(text)
print("tree:", sum(float(o.findtext("total")) for o in root.iter("order")))


# Event (push): the parser calls the handler for each start tag, text and end tag.
class Totals(xml.sax.ContentHandler):
    def __init__(self):
        super().__init__()
        self.sum, self.inside, self.buffer = 0.0, False, []

    def startElement(self, name, attrs):
        if name == "total":
            self.inside, self.buffer = True, []

    def characters(self, content):
        if self.inside:
            self.buffer.append(content)

    def endElement(self, name):
        if name == "total":
            self.sum += float("".join(self.buffer))
            self.inside = False


handler = Totals()
xml.sax.parseString(text, handler)
print("event:", handler.sum)

# Pull: the program asks for the next event, and clears each order after use.
total = 0.0
for event, element in ET.iterparse(io.BytesIO(text), events=("end",)):
    if element.tag == "order":
        total += float(element.findtext("total"))
        element.clear()
print("pull:", total)
Output
tree: 33.75
event: 33.75
pull: 33.75
  • Verdict: stdlib. ElementTree.fromstring builds the tree. xml.sax is the event parser: the program gives a handler, and the parser calls startElement, characters and endElement. The handler must keep its own state, here a flag and a buffer, because characters can come in more than one piece. iterparse is a pull parser that also builds the elements: the program reads the events in a loop and clears each order after it uses it. The cleared elements stay in the tree until the end of the document, but they have no children and no text, so the memory stays small for a large file.
JavaGitHub
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;

public class Main {
    static final String TEXT = """
        <orders>
          <order id="1"><total>9.50</total></order>
          <order id="2"><total>20.00</total></order>
          <order id="3"><total>4.25</total></order>
        </orders>""";

    public static void main(String[] args) throws Exception {
        // Tree: DOM.
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(TEXT)));
        NodeList totals = doc.getElementsByTagName("total");
        double sum = 0;
        for (int i = 0; i < totals.getLength(); i++) {
            sum += Double.parseDouble(totals.item(i).getTextContent());
        }
        System.out.println("tree (DOM): " + sum);

        // Event (push): SAX calls the handler.
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        double[] pushed = {0};
        spf.newSAXParser().parse(new InputSource(new StringReader(TEXT)), new DefaultHandler() {
            StringBuilder text;

            @Override
            public void startElement(String uri, String local, String qName, Attributes atts) {
                if (qName.equals("total")) text = new StringBuilder();
            }

            @Override
            public void characters(char[] ch, int start, int length) {
                if (text != null) text.append(ch, start, length);
            }

            @Override
            public void endElement(String uri, String local, String qName) {
                if (qName.equals("total")) {
                    pushed[0] += Double.parseDouble(text.toString());
                    text = null;
                }
            }
        });
        System.out.println("event (SAX): " + pushed[0]);

        // Pull: StAX, the program calls next().
        XMLInputFactory xif = XMLInputFactory.newInstance();
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        XMLStreamReader r = xif.createXMLStreamReader(new StringReader(TEXT));
        double pulled = 0;
        while (r.hasNext()) {
            if (r.next() == XMLStreamConstants.START_ELEMENT && r.getLocalName().equals("total")) {
                pulled += Double.parseDouble(r.getElementText());
            }
        }
        System.out.println("pull (StAX): " + pulled);
    }
}
Output
tree (DOM): 33.75
event (SAX): 33.75
pull (StAX): 33.75
  • Verdict: stdlib. The JDK has all three models in the module java.xml. DocumentBuilder builds a DOM tree. SAXParser pushes the events to a DefaultHandler, and the handler collects the text of total because characters can come in pieces. XMLStreamReader of StAX is a pull parser: the loop calls next, and getElementText reads the text of the current element. Each factory turns off DTDs, for the reasons on the XML page.
using System.Globalization;
using System.Xml;
using System.Xml.Linq;

string text = """
    <orders>
      <order id="1"><total>9.50</total></order>
      <order id="2"><total>20.00</total></order>
      <order id="3"><total>4.25</total></order>
    </orders>
    """;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

// Tree: LINQ to XML loads the whole document.
XDocument doc = XDocument.Parse(text);
decimal tree = doc.Descendants("total").Sum(t => (decimal)t);
Console.WriteLine($"tree: {tree}");

// Pull: XmlReader moves forward one node at a time.
decimal pulled = 0;
using (XmlReader reader = XmlReader.Create(new StringReader(text)))
{
    while (reader.Read())
    {
        if (reader.NodeType == XmlNodeType.Element && reader.Name == "total")
        {
            pulled += decimal.Parse(reader.ReadElementContentAsString(), CultureInfo.InvariantCulture);
        }
    }
}
Console.WriteLine($"pull: {pulled}");

// Mixed: pull to each order, then load only that element as a tree.
using (XmlReader reader = XmlReader.Create(new StringReader(text)))
{
    while (!reader.EOF)
    {
        if (reader.NodeType == XmlNodeType.Element && reader.Name == "order")
        {
            var order = (XElement)XNode.ReadFrom(reader);
            Console.WriteLine($"order {(string?)order.Attribute("id")}: {(decimal)order.Element("total")!}");
        }
        else
        {
            reader.Read();
        }
    }
}
Output
tree: 33.75
pull: 33.75
order 1: 9.50
order 2: 20.00
order 3: 4.25
  • Verdict: stdlib. XDocument.Parse builds the whole tree. XmlReader is the pull parser of .NET: each call to Read moves to the next node, and the program reads the node where the reader stands. XNode.ReadFrom reads the element at the current position of the reader as a small tree and moves the reader past it. This mix gives the convenience of a tree for each record and the memory use of a stream for the file.
package main

import (
	"encoding/xml"
	"fmt"
	"io"
	"strconv"
	"strings"
)

const text = `<orders>
  <order id="1"><total>9.50</total></order>
  <order id="2"><total>20.00</total></order>
  <order id="3"><total>4.25</total></order>
</orders>`

type Order struct {
	ID    string  `xml:"id,attr"`
	Total float64 `xml:"total"`
}

func main() {
	// Tree: Unmarshal the whole document into structs.
	var all struct {
		Orders []Order `xml:"order"`
	}
	if err := xml.Unmarshal([]byte(text), &all); err != nil {
		panic(err)
	}
	sum := 0.0
	for _, o := range all.Orders {
		sum += o.Total
	}
	fmt.Println("tree:", sum)

	// Pull: ask the decoder for each token.
	d := xml.NewDecoder(strings.NewReader(text))
	pulled := 0.0
	for {
		tok, err := d.Token()
		if err == io.EOF {
			break
		}
		if t, ok := tok.(xml.StartElement); ok && t.Name.Local == "total" {
			var s string
			if err := d.DecodeElement(&s, &t); err != nil {
				panic(err)
			}
			v, _ := strconv.ParseFloat(s, 64)
			pulled += v
		}
	}
	fmt.Println("pull:", pulled)

	// Mixed: pull to each order, then decode only that element.
	d = xml.NewDecoder(strings.NewReader(text))
	for {
		tok, err := d.Token()
		if err == io.EOF {
			break
		}
		if t, ok := tok.(xml.StartElement); ok && t.Name.Local == "order" {
			var o Order
			if err := d.DecodeElement(&o, &t); err != nil {
				panic(err)
			}
			fmt.Printf("order %s: %.2f\n", o.ID, o.Total)
		}
	}
}
Output
tree: 33.75
pull: 33.75
order 1: 9.50
order 2: 20.00
order 3: 4.25
  • Verdict: stdlib. xml.Unmarshal reads the whole document into structs, which is a tree in the form of the program types. Decoder.Token is a pull parser: each call returns the next token, a StartElement, an EndElement, CharData, a Comment or a ProcInst. DecodeElement reads the element at the current position into a value. The last loop mixes the two: it pulls to each order and decodes only that element, so the program never holds the whole file. Go has no push parser in the standard library.
  • Pull parsers for other data. A tokenizer of a programming language is a pull parser: the syntax analyzer asks for the next token. An iterator over the lines of a file is the same idea at a smaller scale.
  • Filters and pipelines. An event handler can pass the events on to another handler, after it changes some of them. SAX calls such a handler a filter. A program can chain filters, and the document never needs to be in memory.
  • Lazy trees. Some libraries build a tree only for the parts that the program reads, or map the nodes to offsets in the text. This is between the tree and the stream models.
  • Writers. The same split applies to output. A program can build a tree and serialise it, or call a stream writer, such as XMLStreamWriter in Java or XmlWriter in .NET, for each element. A stream writer can write a file of any size.

Pitfalls

  • A tree for a large file. The tree of a very large file does not fit in memory. The SAX project gives the example: "If your XML document were 20MB large (or even just 2MB), it would be very inefficient to construct and traverse an in-memory parse tree just to locate this one piece of contextual information".1 Use a stream for large or unbounded input.
  • Text in pieces. An event or pull parser can split the text of one element into several events.3 A program that uses only the first piece reads Tea instead of Tea & cake. Collect the text until the end tag, or use a method that reads the whole text of an element, such as getElementText in StAX.
  • iterparse keeps the tree. Python iterparse builds the tree as it reads, but "The tree is only built incrementally, it is not freed incrementally".5 Without a call to clear on each processed element, it uses as much memory as a tree parser.
  • State in a handler. An event handler that keeps the state in flags breaks when the document has nested elements with the same name, or when an element appears in an unexpected place. Keep a stack of the open elements, or use a pull parser.
  • Errors after the work. A stream parser finds an error in the middle or at the end of the document, after the program has already used the first records. A tree parser fails before the program sees any data. When a partial result is a problem, validate the input first, or write the results in a transaction.
  • Whitespace events. The line feeds and spaces between elements are text. A stream program that expects the next event to be a start tag gets a text event instead. Skip whitespace-only text, as the method nextTag of StAX does.

Cost

Let n be the size of the text. All three models read each byte once, so the time is O(n). A tree uses O(n) memory, with a large constant, because each node is an object with pointers to its parent, its children and its siblings. An event or pull parser uses memory in proportion to the depth of nesting and the size of the largest token, not the size of the document. The mixed pattern uses memory in proportion to the largest record.

History

The XML-DEV mailing list started the design of SAX on 13 December 1997. Peter Murray-Rust, the author of the XML browser JUMBO, wanted one event-based API for all Java XML parsers, and David Megginson coordinated the discussion and wrote the proposal.8 The first draft came out on 12 January 1998, and SAX 1.0 "was released on Monday 11 May 1998, less than five months after SAX was first proposed."8 SAX was "the first widely adopted API for XML in Java, and is a “de facto” standard", and the current version is SAX 2.0.1.9 The Java platform added StAX, the pull API of the package javax.xml.stream.2

References

  1. SAX project, Events vs. Trees, the whole page
  2. Java SE 25 API, javax.xml.stream.XMLStreamReader, the interface description
  3. Java SE 25 API, org.xml.sax.ContentHandler, characters
  4. .NET API documentation, XmlReader Class, the summary and the remarks
  5. The Python Standard Library, xml.etree.ElementTree, Python 3.14, Pull API for non-blocking parsing; iterparse; XMLPullParser Objects
  6. Go standard library, package encoding/xml, Decoder.Token; Decoder.DecodeElement; Unmarshal
  7. The Python Standard Library, xml.sax, Python 3.14, the module description
  8. SAX project, SAX 1.0, Genesis, the whole page
  9. SAX project, About SAX, the whole page

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/26BBYN/text.yaml