DOM Tree Parsing
domdocument_loadxml / getElementsByTagName / savexml
DOM-style XML parsing: the whole document loads into an in-memory node tree with random access to any element, attribute or text node, and modifications serialize back to XML. One of the two big philosophies, opposite to streaming (XMLReader, see xmlreader_writer).
C C23
#include <stdio.h>
#include <string.h>
/* Minimal teaching XML scanner over a fixed, well-formed document:
element names, attributes, text nodes. Production C uses libxml2. */
typedef struct {
char key[64];
char val[64];
} Attr;
static const char *CURSOR;
static void skip_ws(void) {
while (*CURSOR == ' ' || *CURSOR == '\n' || *CURSOR == '\r' || *CURSOR == '\t') CURSOR++;
}
/* Copy the quoted attribute value at the cursor (after the = sign). */
static void read_value(char *out, size_t cap) {
char quote = *CURSOR++;
size_t n = 0;
while (*CURSOR && *CURSOR != quote && n + 1 < cap) out[n++] = *CURSOR++;
out[n] = '\0';
if (*CURSOR == quote) CURSOR++;
}
/* Parse the next <name attr="value"> start tag; returns 0 at end of input. */
static int next_start(char *name, size_t ncap, Attr attrs[], int max, int *nattrs) {
skip_ws();
*nattrs = 0;
while (*CURSOR && *CURSOR != '<') {
CURSOR++;
skip_ws();
}
if (*CURSOR != '<') return 0;
CURSOR++; /* past < */
if (*CURSOR == '?') { /* skip the declaration prolog */
while (*CURSOR && *CURSOR != '>') CURSOR++;
return next_start(name, ncap, attrs, max, nattrs);
}
if (*CURSOR == '/') return 0; /* end tag, caller handles */
size_t n = 0;
while (*CURSOR && *CURSOR != ' ' && *CURSOR != '>' && n + 1 < ncap) name[n++] = *CURSOR++;
name[n] = '\0';
while (*CURSOR && *CURSOR != '>') {
if (*CURSOR == '/') { while (*CURSOR && *CURSOR != '>') CURSOR++; break; }
skip_ws();
char key[64];
size_t k = 0;
while (*CURSOR && *CURSOR != '=' && *CURSOR != '>' && k + 1 < sizeof key) key[k++] = *CURSOR++;
key[k] = '\0';
if (*CURSOR == '=') {
CURSOR++;
char val[64];
read_value(val, sizeof val);
if (*nattrs < max) {
snprintf(attrs[*nattrs].key, sizeof attrs[*nattrs].key, "%s", key);
snprintf(attrs[*nattrs].val, sizeof attrs[*nattrs].val, "%s", val);
(*nattrs)++;
}
}
}
if (*CURSOR == '>') CURSOR++;
return 1;
}
/* Text up to the next < (trimmed). */
static void read_text(char *out, size_t cap) {
while (*CURSOR == ' ' || *CURSOR == '\n') CURSOR++;
size_t n = 0;
while (*CURSOR && *CURSOR != '<' && n + 1 < cap) out[n++] = *CURSOR++;
while (n > 0 && (out[n - 1] == ' ' || out[n - 1] == '\n')) out[--n] = '\0';
out[n] = '\0';
}
int main(void) {
const char *xml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<catalog>\n"
" <book id=\"bk101\" lang=\"php\">\n"
" <title>PHP Essentials</title>\n"
" </book>\n"
" <book id=\"bk102\" lang=\"rust\">\n"
" <title>Rust in Action</title>\n"
" </book>\n"
"</catalog>";
CURSOR = xml;
char name[64], title[64];
Attr attrs[8];
int nattrs, books = 0;
while (next_start(name, sizeof name, attrs, 8, &nattrs)) {
if (strcmp(name, "book") == 0) {
const char *id = "", *lang = "";
for (int i = 0; i < nattrs; i++) {
if (strcmp(attrs[i].key, "id") == 0) id = attrs[i].val;
if (strcmp(attrs[i].key, "lang") == 0) lang = attrs[i].val;
}
books++;
/* scan forward for the title child text */
char inner[64];
while (next_start(inner, sizeof inner, attrs, 8, &nattrs)) {
if (strcmp(inner, "title") == 0) {
read_text(title, sizeof title);
printf("book[%d] id=%s lang=%s title=%s\n", books - 1, id, lang, title);
}
}
CURSOR = strstr(CURSOR, "<book");
if (CURSOR == NULL) break;
}
}
printf("books: %d\n", books);
return 0;
}
book[0] id=bk101 lang=php title=PHP Essentials book[1] id=bk102 lang=rust title=Rust in Action books: 2
C++ C++26
#include <cstdio>
#include <cstring>
// Minimal teaching XML scanner (elements, attributes, text) with a cursor.
// Production C++ uses libxml2/pugixml; this shows what a parser fundamentally does.
static const char *CURSOR;
static void skipWs() {
while (*CURSOR == ' ' || *CURSOR == '\n' || *CURSOR == '\r' || *CURSOR == '\t') CURSOR++;
}
static void readValue(char *out, int cap) {
char quote = *CURSOR++;
int n = 0;
while (*CURSOR && *CURSOR != quote && n + 1 < cap) out[n++] = *CURSOR++;
out[n] = '\0';
if (*CURSOR == quote) CURSOR++;
}
// attribute lookup within the most recent start tag
static char AKEY[8][64], AVAL[8][64];
static int NATTRS;
static bool nextStart(char *name) {
skipWs();
while (*CURSOR && *CURSOR != '<') {
CURSOR++;
skipWs();
}
if (*CURSOR != '<') return false;
CURSOR++;
if (*CURSOR == '?') {
while (*CURSOR && *CURSOR != '>') CURSOR++;
return nextStart(name);
}
if (*CURSOR == '/') return false;
int n = 0;
while (*CURSOR && *CURSOR != ' ' && *CURSOR != '>' && n + 1 < 64) name[n++] = *CURSOR++;
name[n] = '\0';
NATTRS = 0;
while (*CURSOR && *CURSOR != '>') {
if (*CURSOR == '/') {
while (*CURSOR && *CURSOR != '>') CURSOR++;
break;
}
skipWs();
char key[64];
int k = 0;
while (*CURSOR && *CURSOR != '=' && *CURSOR != '>' && k + 1 < 64) key[k++] = *CURSOR++;
key[k] = '\0';
if (*CURSOR == '=') {
CURSOR++;
char val[64];
readValue(val, 64);
if (NATTRS < 8) {
std::strcpy(AKEY[NATTRS], key);
std::strcpy(AVAL[NATTRS], val);
NATTRS++;
}
}
}
if (*CURSOR == '>') CURSOR++;
return true;
}
static void readText(char *out, int cap) {
while (*CURSOR == ' ' || *CURSOR == '\n') CURSOR++;
int n = 0;
while (*CURSOR && *CURSOR != '<' && n + 1 < cap) out[n++] = *CURSOR++;
while (n > 0 && (out[n - 1] == ' ' || out[n - 1] == '\n')) out[--n] = '\0';
out[n] = '\0';
}
int main() {
const char *xml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<catalog>\n"
" <book id=\"bk101\" lang=\"php\">\n"
" <title>PHP Essentials</title>\n"
" </book>\n"
" <book id=\"bk102\" lang=\"rust\">\n"
" <title>Rust in Action</title>\n"
" </book>\n"
"</catalog>";
CURSOR = xml;
char name[64], title[64];
int books = 0;
while (nextStart(name)) {
if (std::strcmp(name, "book") == 0) {
const char *id = "", *lang = "";
for (int i = 0; i < NATTRS; i++) {
if (std::strcmp(AKEY[i], "id") == 0) id = AVAL[i];
if (std::strcmp(AKEY[i], "lang") == 0) lang = AVAL[i];
}
char inner[64];
while (nextStart(inner)) {
if (std::strcmp(inner, "title") == 0) {
readText(title, 64);
std::printf("book[%d] id=%s lang=%s title=%s\n", books, id, lang, title);
}
}
books++;
CURSOR = std::strstr(CURSOR, "<book");
if (CURSOR == nullptr) break;
}
}
std::printf("books: %d\n", books);
return 0;
}
book[0] id=bk101 lang=php title=PHP Essentials book[1] id=bk102 lang=rust title=Rust in Action books: 2
C# v11.0.100
using System.Xml;
string xml = """
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<book id="bk101" lang="php">
<title>PHP Essentials</title>
</book>
<book id="bk102" lang="rust">
<title>Rust in Action</title>
</book>
</catalog>
""";
// DOM parsing: XmlDocument.LoadXml builds the whole node tree in memory
var doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList books = doc.SelectNodes("//book")!;
Console.WriteLine($"books: {books.Count}");
Console.WriteLine($"book[0] id={books[0]!.Attributes["id"]!.Value} lang={books[0]!.Attributes["lang"]!.Value} title={books[0]!["title"]!.InnerText}");
XmlElement third = doc.CreateElement("book");
third.SetAttribute("id", "bk103");
third.SetAttribute("lang", "go");
XmlElement t = doc.CreateElement("title");
t.InnerText = "Go in Practice";
third.AppendChild(t);
doc.DocumentElement!.AppendChild(third);
Console.WriteLine($"after append: {doc.SelectNodes("//book")!.Count}");
foreach (XmlNode b in doc.SelectNodes("//book")!) {
Console.WriteLine($" {b.Attributes["id"]!.Value} / {b["title"]!.InnerText}");
}
books: 2 book[0] id=bk101 lang=php title=PHP Essentials after append: 3 bk101 / PHP Essentials bk102 / Rust in Action bk103 / Go in Practice
Go v1.27.4
package main
import (
"bytes"
"encoding/xml"
"fmt"
)
// Go uses struct mapping rather than a DOM tree: Unmarshal decodes the
// document straight into typed values (a different model, same wire format).
type Catalog struct {
Books []Book `xml:"book"`
}
type Book struct {
ID string `xml:"id,attr"`
Lang string `xml:"lang,attr"`
Title string `xml:"title"`
}
func main() {
xmlData := `<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<book id="bk101" lang="php">
<title>PHP Essentials</title>
</book>
<book id="bk102" lang="rust">
<title>Rust in Action</title>
</book>
</catalog>`
var cat Catalog
if err := xml.Unmarshal([]byte(xmlData), &cat); err != nil {
panic(err)
}
fmt.Println("books:", len(cat.Books))
fmt.Printf("book[0] id=%s lang=%s title=%s\n", cat.Books[0].ID, cat.Books[0].Lang, cat.Books[0].Title)
cat.Books = append(cat.Books, Book{ID: "bk103", Lang: "go", Title: "Go in Practice"})
fmt.Println("after append:", len(cat.Books))
for _, b := range cat.Books {
fmt.Printf(" %s / %s\n", b.ID, b.Title)
}
// marshal the mapped structs back to XML wire format
out, _ := xml.MarshalIndent(cat, "", " ")
fmt.Println("serialize:", bytes.Contains(out, []byte("bk103")), "bytes:", len(out))
}
books: 2 book[0] id=bk101 lang=php title=PHP Essentials after append: 3 bk101 / PHP Essentials bk102 / Rust in Action bk103 / Go in Practice serialize: true bytes: 245
Java v27.0.1
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
public class Main {
public static void main(String[] args) throws Exception {
String xml = """
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<book id="bk101" lang="php">
<title>PHP Essentials</title>
</book>
<book id="bk102" lang="rust">
<title>Rust in Action</title>
</book>
</catalog>
""";
// DOM parsing: DocumentBuilder.parse builds the whole node tree in memory
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(xml)));
NodeList books = doc.getElementsByTagName("book");
System.out.println("books: " + books.getLength());
Element first = (Element) books.item(0);
System.out.println("book[0] id=" + first.getAttribute("id") + " lang=" + first.getAttribute("lang")
+ " title=" + first.getElementsByTagName("title").item(0).getTextContent());
Element third = doc.createElement("book");
third.setAttribute("id", "bk103");
third.setAttribute("lang", "go");
Element t = doc.createElement("title");
t.setTextContent("Go in Practice");
third.appendChild(t);
doc.getDocumentElement().appendChild(third);
System.out.println("after append: " + doc.getElementsByTagName("book").getLength());
for (int i = 0; i < doc.getElementsByTagName("book").getLength(); i++) {
Element b = (Element) doc.getElementsByTagName("book").item(i);
System.out.println(" " + b.getAttribute("id") + " / " + b.getElementsByTagName("title").item(0).getTextContent());
}
}
}
books: 2 book[0] id=bk101 lang=php title=PHP Essentials after append: 3 bk101 / PHP Essentials bk102 / Rust in Action bk103 / Go in Practice
JavaScript v26.13.1
// Minimal XML tokenizer + tree fold in plain JS. Browser code uses the
// DOMParser API (same document model); Node has no built-in XML parser,
// so this shows what a parser fundamentally does, notes point at xmldom.
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<book id="bk101" lang="php">
<title>PHP Essentials</title>
</book>
<book id="bk102" lang="rust">
<title>Rust in Action</title>
</book>
</catalog>`;
// Token stream: {type: 'start'|'end'|'text', name, attrs}
function* tokenize(src) {
let i = 0;
while (i < src.length) {
if (src[i] !== '<') {
let text = '';
while (i < src.length && src[i] !== '<') text += src[i++];
const t = text.trim();
if (t) yield { type: 'text', value: t };
continue;
}
if (src.startsWith('<?', i)) { i = src.indexOf('>', i) + 1; continue; } // declaration
if (src.startsWith('</', i)) { // end tag
const e = src.indexOf('>', i);
yield { type: 'end', name: src.slice(i + 2, e) };
i = e + 1;
continue;
}
// start tag: <name attr="v" ...> or <name/>
const m = src.slice(i).match(/^<([^\s/>]+)((?:\s+[^\s=]+="[^"]*")*)\s*(\/?)>/);
if (!m) break;
const attrs = {};
for (const a of m[2].matchAll(/([^\s=]+)="([^"]*)"/g)) attrs[a[1]] = a[2];
yield { type: 'start', name: m[1], attrs };
if (m[3] === '/') yield { type: 'end', name: m[1] };
i += m[0].length;
}
}
// DOM layer: fold the token stream into a tree with a stack
const stack = [{ name: '#doc', children: [], attrs: {} }];
for (const t of tokenize(xml)) {
if (t.type === 'start') {
const node = { name: t.name, attrs: t.attrs, children: [], text: '' };
stack[stack.length - 1].children.push(node);
stack.push(node);
} else if (t.type === 'end') {
stack.pop();
} else {
stack[stack.length - 1].text += t.value;
}
}
const root = stack[0].children[0];
const books = root.children.filter((c) => c.name === 'book');
console.log('books:', books.length);
console.log('first:', books[0].attrs.id, '/', books[0].children[0].text);
console.log('second:', books[1].attrs.id, '/', books[1].children[0].text);
books: 2 first: bk101 / PHP Essentials second: bk102 / Rust in Action
PHP v8.6.0
// DOM parsing: loadXML builds the whole node tree in memory; DOMDocument
// gives random access (getElementsByTagName) and node operations append
$xml = <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<book id="bk101" lang="php">
<title>PHP Essentials</title>
</book>
<book id="bk102" lang="rust">
<title>Rust in Action</title>
</book>
</catalog>
XML;
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$doc->loadXML($xml);
$books = $doc->getElementsByTagName('book');
echo "books: ", $books->length, PHP_EOL;
$first = $books->item(0);
echo "book[0] id=", $first->getAttribute('id'), " lang=", $first->getAttribute('lang'),
" title=", $first->getElementsByTagName('title')->item(0)->textContent, PHP_EOL;
$third = $doc->createElement('book');
$third->setAttribute('id', 'bk103');
$third->setAttribute('lang', 'go');
$t = $doc->createElement('title');
$t->appendChild($doc->createTextNode('Go in Practice')); // text is a node too
$third->appendChild($t);
$doc->documentElement->appendChild($third);
echo "after append: ", $doc->getElementsByTagName('book')->length, PHP_EOL;
foreach ($doc->getElementsByTagName('book') as $b) {
echo " ", $b->getAttribute('id'), " / ", $b->getElementsByTagName('title')->item(0)->textContent, PHP_EOL;
}
books: 2 book[0] id=bk101 lang=php title=PHP Essentials after append: 3 bk101 / PHP Essentials bk102 / Rust in Action bk103 / Go in Practice
Python v3.15.2
from xml.dom import minidom
xml = """<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<book id="bk101" lang="php">
<title>PHP Essentials</title>
</book>
<book id="bk102" lang="rust">
<title>Rust in Action</title>
</book>
</catalog>"""
# DOM parsing: parseString builds the whole node tree in memory
doc = minidom.parseString(xml)
books = doc.getElementsByTagName("book")
print("books:", books.length)
first = books[0]
print("book[0] id=%s lang=%s title=%s" % (
first.getAttribute("id"), first.getAttribute("lang"),
first.getElementsByTagName("title")[0].firstChild.data))
third = doc.createElement("book")
third.setAttribute("id", "bk103")
third.setAttribute("lang", "go")
t = doc.createElement("title")
t.appendChild(doc.createTextNode("Go in Practice")) # text is a node too
third.appendChild(t)
doc.documentElement.appendChild(third)
print("after append:", doc.getElementsByTagName("book").length)
for b in doc.getElementsByTagName("book"):
print(" %s / %s" % (b.getAttribute("id"), b.getElementsByTagName("title")[0].firstChild.data))
books: 2 book[0] id=bk101 lang=php title=PHP Essentials after append: 3 bk101 / PHP Essentials bk102 / Rust in Action bk103 / Go in Practice
Rust v1.99.1
// Rust quick-xml is an event (pull) parser, not a DOM: you fold the token
// stream into your own tree or handle events as they come (different model).
use quick_xml::events::Event;
use quick_xml::Reader;
fn main() {
let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<book id="bk101" lang="php">
<title>PHP Essentials</title>
</book>
<book id="bk102" lang="rust">
<title>Rust in Action</title>
</book>
</catalog>"#;
let mut reader = Reader::from_str(xml);
reader.config_mut().trim_text(true);
let mut books: Vec<(String, String, String)> = Vec::new(); // (id, lang, title)
let mut current_book: Option<(String, String)> = None;
let mut in_title = false;
loop {
match reader.read_event() {
Ok(Event::Start(e)) => match e.name().as_ref() {
b"book" => {
let mut id = String::new();
let mut lang = String::new();
for attr in e.attributes() {
let a = attr.unwrap();
match a.key.as_ref() {
b"id" => id = a.unescape_value().unwrap().into_owned(),
b"lang" => lang = a.unescape_value().unwrap().into_owned(),
_ => {}
}
}
current_book = Some((id, lang));
}
b"title" => in_title = true,
_ => {}
},
Ok(Event::Text(t)) if in_title => {
let title = t.xml_content().unwrap().into_owned();
let (id, lang) = current_book.take().unwrap();
books.push((id, lang, title));
in_title = false;
}
Ok(Event::Eof) => break,
_ => {}
}
}
// the "DOM operation" equivalent: push a new book into the Vec
books.push(("bk103".into(), "go".into(), "Go in Practice".into()));
println!("books: {}", books.len() - 1);
println!("book[0] id={} lang={} title={}", books[0].0, books[0].1, books[0].2);
println!("after append: {}", books.len());
for (id, _lang, title) in &books {
println!(" {} / {}", id, title);
}
}
books: 2 book[0] id=bk101 lang=php title=PHP Essentials after append: 3 bk101 / PHP Essentials bk102 / Rust in Action bk103 / Go in Practice
TypeScript v26.13.1
// Same tokenizer + tree fold as the JavaScript block, typed. Browser code
// uses DOMParser; Node has no built-in XML parser (third-party in the notes).
interface Token {
type: 'start' | 'end' | 'text';
name?: string;
attrs?: Record<string, string>;
value?: string;
}
interface Node_ {
name: string;
attrs: Record<string, string>;
children: Node_[];
text: string;
}
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<book id="bk101" lang="php">
<title>PHP Essentials</title>
</book>
<book id="bk102" lang="rust">
<title>Rust in Action</title>
</book>
</catalog>`;
function* tokenize(src: string): Generator<Token> {
let i = 0;
while (i < src.length) {
if (src[i] !== '<') {
let text = '';
while (i < src.length && src[i] !== '<') text += src[i++];
const t = text.trim();
if (t) yield { type: 'text', value: t };
continue;
}
if (src.startsWith('<?', i)) { i = src.indexOf('>', i) + 1; continue; }
if (src.startsWith('</', i)) {
const e = src.indexOf('>', i);
yield { type: 'end', name: src.slice(i + 2, e) };
i = e + 1;
continue;
}
const m = src.slice(i).match(/^<([^\s/>]+)((?:\s+[^\s=]+="[^"]*")*)\s*(\/?)>/);
if (!m) break;
const attrs: Record<string, string> = {};
for (const a of m[2].matchAll(/([^\s=]+)="([^"]*)"/g)) attrs[a[1]] = a[2];
yield { type: 'start', name: m[1], attrs };
if (m[3] === '/') yield { type: 'end', name: m[1] };
i += m[0].length;
}
}
// DOM layer: fold the token stream into a tree with a stack
const stack: Node_[] = [{ name: '#doc', attrs: {}, children: [], text: '' }];
for (const t of tokenize(xml)) {
if (t.type === 'start') {
const node: Node_ = { name: t.name!, attrs: t.attrs!, children: [], text: '' };
stack[stack.length - 1].children.push(node);
stack.push(node);
} else if (t.type === 'end') {
stack.pop();
} else {
stack[stack.length - 1].text += t.value!;
}
}
const root = stack[0].children[0];
const books = root.children.filter((c) => c.name === 'book');
console.log('books:', books.length);
console.log('first:', books[0].attrs.id, '/', books[0].children[0].text);
console.log('second:', books[1].attrs.id, '/', books[1].children[0].text);
books: 2 first: bk101 / PHP Essentials second: bk102 / Rust in Action
Language differences
Three XML philosophies on one stage: DOM (this entry, whole tree in memory, random access, serializable back) vs object access (SimpleXML/ElementTree, see simplexml) vs streaming (XMLReader/SAX/iterparse, see xmlreader_writer) — pick streaming for large files and memory-sensitive cases, DOM for complex queries and rewriting.
PHP: DOMDocument is a standard extension (libxml2 core); getElementsByTagName returns a live DOMNodeList (length changes right after append); loadXML takes a string, load takes a file; pretty output needs formatOutput=true.
C: no XML in the standard library — the example hand-writes a minimal scanner (elements/attributes/text, ~80 lines); production uses libxml2 (xmlReadMemory/tree).
C++: same hand-rolled scanner as C; production uses libxml2 or pugixml (DOM).
C#: XmlDocument is DOM-style (SelectNodes supports XPath); the sibling LINQ to XML (XDocument) is in simplexml.
Go: encoding/xml has no DOM — it is struct mapping (Unmarshal decodes into typed values); a different model, same wire format; third-party xmlpath for a real DOM.
Java: javax.xml.parsers DOM (the W3C DOM standard API); XPath lives in javax.xml.xpath.
JavaScript: the browser DOMParser is the standard XML DOM API (DOM-style); Node has no built-in XML parser — the example hand-writes a tokenizer + stack fold to show how DOM building fundamentally works; production uses xmldom/fast-xml-parser.
Python: xml.dom.minidom is the standard-library DOM counterpart (same-named getElementsBy* API); the more common object-style is ElementTree (see simplexml).
Rust: no XML in the standard library — quick-xml is an event (pull) parser (different model: fold the token stream into your own tree); DOM-style third parties are minidom/roxmltree.
TypeScript: same as JavaScript.