Simple XML Object Access

simplexml_load_string / xpath / addchild

SimpleXML object-style XML handling: the document maps to an object tree you traverse with -> and property syntax, plus xpath queries. One of PHP's two XML philosophies alongside DOM — object access buys brevity, node operations buy control.

C C23

C23
#include <stdio.h>
#include <string.h>

/* Same minimal scanner, attribute-access emphasis: look up elements and
   pull their attributes (the SimpleXML-style read path in ~40 lines). */

typedef struct {
    char key[64];
    char val[64];
} Attr;

static const char *CURSOR;
static char AKEY[8][64], AVAL[8][64];
static int NATTRS;

static void skip_ws(void) {
    while (*CURSOR == ' ' || *CURSOR == '\n' || *CURSOR == '\r' || *CURSOR == '\t') CURSOR++;
}

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++;
}

static int next_start(char *name) {
    skip_ws();
    NATTRS = 0;
    while (*CURSOR && *CURSOR != '<') CURSOR++;
    if (*CURSOR != '<') return 0;
    CURSOR++;
    if (*CURSOR == '?') {
        while (*CURSOR && *CURSOR != '>') CURSOR++;
        return next_start(name);
    }
    if (*CURSOR == '/') return 0;
    size_t n = 0;
    while (*CURSOR && *CURSOR != ' ' && *CURSOR != '>' && n + 1 < 64) 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 < 8) {
                snprintf(AKEY[NATTRS], 64, "%s", key);
                snprintf(AVAL[NATTRS], 64, "%s", val);
                NATTRS++;
            }
        }
    }
    if (*CURSOR == '>') CURSOR++;
    return 1;
}

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\"><title>PHP Essentials</title></book>\n"
        "  <book id=\"bk102\" lang=\"rust\"><title>Rust in Action</title></book>\n"
        "</catalog>";
    CURSOR = xml;
    char name[64], title[64];
    int books = 0;
    char first_id[64] = "", first_title[64] = "";
    while (next_start(name)) {
        if (strcmp(name, "book") == 0) {
            const char *id = "", *lang = "";
            for (int i = 0; i < NATTRS; i++) {
                if (strcmp(AKEY[i], "id") == 0) id = AVAL[i];
                if (strcmp(AKEY[i], "lang") == 0) lang = AVAL[i];
            }
            books++;
            if (books == 1) {
                /* snapshot the first book now: AKEY/AVAL get overwritten on
                   the next start tag, so copy instead of keeping pointers */
                snprintf(first_id, sizeof first_id, "%s", id);
            }
            char inner[64];
            while (next_start(inner)) {
                if (strcmp(inner, "title") == 0 && books == 1) {
                    read_text(first_title, sizeof first_title);
                }
            }
            CURSOR = strstr(CURSOR, "<book");
            if (CURSOR == NULL) break;
        }
    }
    printf("books: %d\n", books);
    printf("first: %s / %s\n", first_id, first_title);
    return 0;
}
Output
books: 2
first: bk101 / PHP Essentials

C++ C++26

C++26
#include <cstdio>
#include <cstring>

// Same scanner in C++ style, attribute-access emphasis.

static const char *CURSOR;
static char AKEY[8][64], AVAL[8][64];
static int NATTRS;

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++;
}

static bool nextStart(char *name) {
    skipWs();
    NATTRS = 0;
    while (*CURSOR && *CURSOR != '<') CURSOR++;
    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';
    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\"><title>PHP Essentials</title></book>\n"
        "  <book id=\"bk102\" lang=\"rust\"><title>Rust in Action</title></book>\n"
        "</catalog>";
    CURSOR = xml;
    char name[64], title[64];
    int books = 0;
    char firstId[64] = "", firstTitle[64] = "";
    while (nextStart(name)) {
        if (std::strcmp(name, "book") == 0) {
            const char *id = "";
            for (int i = 0; i < NATTRS; i++)
                if (std::strcmp(AKEY[i], "id") == 0) id = AVAL[i];
            if (books == 0) std::snprintf(firstId, sizeof firstId, "%s", id);
            books++;
            char inner[64];
            while (nextStart(inner)) {
                if (std::strcmp(inner, "title") == 0 && books == 1) readText(firstTitle, 64);
            }
            CURSOR = std::strstr(CURSOR, "<book");
            if (CURSOR == nullptr) break;
        }
    }
    std::printf("books: %d\n", books);
    std::printf("first: %s / %s\n", firstId, firstTitle);
    return 0;
}
Output
books: 2
first: bk101 / PHP Essentials

C# v11.0.100

v11.0.100
using System.Xml.Linq;
using System.Xml.XPath;

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>
""";
// LINQ to XML (XDocument): the C# counterpart of SimpleXML's object style
var doc = XDocument.Parse(xml);
var books = doc.Descendants("book");
Console.WriteLine($"books: {books.Count()}");
Console.WriteLine($"first: {books.First().Attribute("id")!.Value} / {books.First().Element("title")!.Value}");
var rust = doc.XPathSelectElement("//book[@lang='rust']/title");
Console.WriteLine($"query: {rust!.Value}");
doc.Root!.Add(new XElement("book", new XAttribute("id", "bk103"), new XAttribute("lang", "go"), new XElement("title", "Go in Practice")));
var last = doc.Descendants("book").Last();
Console.WriteLine($"after: {doc.Descendants("book").Count()} last: {last.Attribute("id")!.Value} / {last.Element("title")!.Value}");
Console.WriteLine("dump: " + last);
Output
books: 2
first: bk101 / PHP Essentials
query: Rust in Action
after: 3 last: bk103 / Go in Practice
dump: <book id="bk103" lang="go">
  <title>Go in Practice</title>
</book>

Go v1.27.4

v1.27.4
package main

import (
	"encoding/xml"
	"fmt"
)

// Go stays with struct mapping: field tags address elements/attributes,
// which reads like object access (the SimpleXML counterpart in stdlib)
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
	xml.Unmarshal([]byte(xmlData), &cat)
	fmt.Println("books:", len(cat.Books))
	fmt.Printf("first: %s / %s\n", cat.Books[0].ID, cat.Books[0].Title)
	// "query": plain slice filtering — Go has no xpath in stdlib
	for _, b := range cat.Books {
		if b.Lang == "rust" {
			fmt.Println("query:", b.Title)
		}
	}
}
Output
books: 2
first: bk101 / PHP Essentials
query: Rust in Action

Java v27.0.1

v27.0.1
import java.io.StringReader;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
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>
""";
        // XPath over a DOM: Java's concise query route (the closest pair to
        // SimpleXML's one-call xpath; Java has no object-style XML tree)
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(new InputSource(new StringReader(xml)));
        XPath xp = XPathFactory.newInstance().newXPath();
        NodeList books = (NodeList) xp.evaluate("//book", doc, XPathConstants.NODESET);
        System.out.println("books: " + books.getLength());
        System.out.println("first: " + books.item(0).getAttributes().getNamedItem("id").getNodeValue()
            + " / " + xp.evaluate("//book[1]/title", doc));
        System.out.println("query: " + xp.evaluate("//book[@lang='rust']/title", doc));
    }
}
Output
books: 2
first: bk101 / PHP Essentials
query: Rust in Action

JavaScript v26.13.1

v26.13.1
// The tokenizer from the DOM entry, this time read object-style: build the
// tree once, then address elements like object properties.
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) {
  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 = {};
    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;
  }
}

// fold into a tree, then read it like SimpleXML does: element proxy + attrs
const stack = [{ name: '#doc', attrs: {}, text: '', children: [] }];
for (const t of tokenize(xml)) {
  if (t.type === 'start') {
    const node = { name: t.name, attrs: t.attrs, text: '', children: [] };
    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 catalog = stack[0].children[0];
const books = catalog.children.filter((c) => c.name === 'book');
console.log('books:', books.length);
console.log('first:', books[0].attrs.id, '/', books[0].children[0].text);
// "query": array find (no xpath in the language itself)
console.log('query:', books.find((b) => b.attrs.lang === 'rust').children[0].text);
Output
books: 2
first: bk101 / PHP Essentials
query: Rust in Action

PHP v8.6.0

v8.6.0
// SimpleXML: element access reads like object property access; xpath
// queries are one call. This is PHP's second XML philosophy beside DOM.
$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;

$sx = simplexml_load_string($xml);
echo "books: ", count($sx->book), PHP_EOL;
echo "first: ", $sx->book[0]['id'], " / ", $sx->book[0]->title, PHP_EOL;
$rust = $sx->xpath('//book[@lang="rust"]/title');
echo "query: ", $rust[0], PHP_EOL;
$go = $sx->addChild('book');
$go->addAttribute('id', 'bk103');
$go->addAttribute('lang', 'go');
$go->addChild('title', 'Go in Practice');
echo "after: ", count($sx->book), " last: ", $sx->book[2]['id'], " / ", $sx->book[2]->title, PHP_EOL;
echo "asXML: ", $sx->book[2]->asXML(), PHP_EOL;
Output
books: 2
first: bk101 / PHP Essentials
query: Rust in Action
after: 3 last: bk103 / Go in Practice
asXML: <book id="bk103" lang="go"><title>Go in Practice</title></book>

Python v3.15.2

v3.15.2
import xml.etree.ElementTree as ET

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>"""

# ElementTree: element access via find/findall + attribute indexing —
# the standard library's answer to SimpleXML's object style
root = ET.fromstring(xml)
books = root.findall("book")
print("books:", len(books))
print("first:", books[0].get("id"), "/", books[0].findtext("title"))
print("query:", root.find("book[@lang='rust']/title").text)
go = ET.SubElement(root, "book", {"id": "bk103", "lang": "go"})
ET.SubElement(go, "title").text = "Go in Practice"
print("after:", len(root.findall("book")), "last:", root.findall("book")[2].get("id"), "/", root.findall("book")[2].findtext("title"))
print("dump:", ET.tostring(root.findall("book")[2]).decode())
Output
books: 2
first: bk101 / PHP Essentials
query: Rust in Action
after: 3 last: bk103 / Go in Practice
dump: <book id="bk103" lang="go"><title>Go in Practice</title></book>

Rust v1.99.1

v1.99.1
// quick-xml: attribute and text access over the event stream (typed Vec
// collection plays the object-tree role; no DOM in quick-xml itself)
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();
    let mut current: 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 = Some((id, lang));
                }
                b"title" => in_title = true,
                _ => {}
            },
            Ok(Event::Text(t)) if in_title => {
                let (id, lang) = current.take().unwrap();
                books.push((id, lang, t.xml_content().unwrap().into_owned()));
                in_title = false;
            }
            Ok(Event::Eof) => break,
            _ => {}
        }
    }
    println!("books: {}", books.len());
    println!("first: {} / {}", books[0].0, books[0].2);
    // "query": iterator filtering (Go/Rust do not ship xpath in stdlib)
    let rust = books.iter().find(|(_, lang, _)| lang == "rust").unwrap();
    println!("query: {}", rust.2);
}
Output
books: 2
first: bk101 / PHP Essentials
query: Rust in Action

TypeScript v26.13.1

v26.13.1
// Typed object-style access over the tokenizer: build the tree once, then
// address elements like object properties.
interface Tok {
  type: 'start' | 'end' | 'text';
  name?: string;
  attrs?: Record<string, string>;
  value?: string;
}
interface El {
  name: string;
  attrs: Record<string, string>;
  text: string;
  children: El[];
}

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<Tok> {
  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;
  }
}

// fold into a tree, then read it like SimpleXML does: element proxy + attrs
const stack: El[] = [{ name: '#doc', attrs: {}, text: '', children: [] }];
for (const t of tokenize(xml)) {
  if (t.type === 'start') {
    const node: El = { name: t.name!, attrs: t.attrs!, text: '', children: [] };
    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 catalog = stack[0].children[0];
const books = catalog.children.filter((c) => c.name === 'book');
console.log('books:', books.length);
console.log('first:', books[0].attrs.id, '/', books[0].children[0].text);
// "query": array find (no xpath in the language itself)
console.log('query:', books.find((b) => b.attrs.lang === 'rust').children[0].text);
Output
books: 2
first: bk101 / PHP Essentials
query: Rust in Action

Language differences

Two philosophies side by side: object access (this entry: ->book[0]['id'] reads in one line) vs node operations (DOMDocument, see xml_dom) — PHP is one of the few languages shipping both in the standard library; other languages map it to object-style/concise-query libraries: ElementTree/XDocument/XPath.

PHP: simplexml_load_string returns a SimpleXMLElement; ->book is an element proxy (iterable, countable); attributes use ['id']; xpath() is one call; addChild/addAttribute support writes; asXML() serializes any node back; since 8.0 the count($sx->book) semantics are stable and $sx->book[0] and foreach both work.

C: no XML in the standard library — a hand-written scanner shows the attribute read path; production uses libxml2 XPath (xmlXPathEval).

C++: same hand-rolled scanner as C; production uses pugixml — its node/attribute API is the closest to SimpleXML's feel anywhere.

C#: LINQ to XML (XDocument) is the standard answer — Descendants/Attribute/Element plus XPathSelectElement; the strongest object feel of the ten.

Go: encoding/xml struct mapping keeps playing object access (field tags are the paths); no stdlib xpath, queries are slice filtering.

Java: no object-style XML tree — DOM plus javax.xml.xpath evaluate is the concise-query route.

JavaScript: the browser DOM has querySelector and XPath (document.evaluate); the example reuses the DOM entry's tokenizer, object-style nodes + array find show the same read path; production uses fast-xml-parser (its object output feels like SimpleXML).

Python: xml.etree.ElementTree is the standard answer — find/findall plus .get/.text/.attrib; find supports a limited XPath subset (usually enough); lxml.etree (third party) for full queries.

Rust: quick-xml event stream + typed Vec collection; no stdlib xpath; DOM-style third party roxmltree (find/descendants feel object-like).

TypeScript: same as JavaScript.