DOM 树解析

domdocument_loadxml / getElementsByTagName / savexml

DOM 派 XML 解析:整棵文档一次性加载为内存节点树,随机访问任意元素/属性/文本,修改后可序列化回写。与流式派(XMLReader,见 xmlreader_writer)构成 XML 处理两大哲学。

C C23

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

/* 教学用极简 XML 扫描器(固定良构输入):元素名、属性、文本节点。
   生产 C 用 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++;
}

/* 复制光标处的引号属性值(已过 = 号)。 */
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++;
}

/* 解析下一个 <name attr="value"> 开始标签;输入结束返回 0。 */
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++; /* 越过 < */
    if (*CURSOR == '?') { /* 跳过声明序言 */
        while (*CURSOR && *CURSOR != '>') CURSOR++;
        return next_start(name, ncap, attrs, max, nattrs);
    }
    if (*CURSOR == '/') return 0; /* 结束标签由调用方处理 */
    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;
}

/* 文本到下一个 < 为止(去除首尾空白)。 */
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++;
            /* 向前扫描 title 子元素文本 */
            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

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

// 教学用极简 XML 扫描器(游标驱动:元素、属性、文本)。
// 生产 C++ 用 libxml2/pugixml;这里展示解析器的本质工作。

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

// 在最近的开始标签内查属性
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

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 解析:XmlDocument.LoadXml 把整棵节点树一次性载入内存
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

v1.27.4
package main

import (
	"bytes"
	"encoding/xml"
	"fmt"
)

// Go 用结构体映射而非 DOM 树:Unmarshal 把文档直接解码为类型化值
//(模型不同,线上格式相同)
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)
	}
	// 把映射后的结构体序列化回 XML 线上格式
	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

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 解析:DocumentBuilder.parse 把整棵节点树一次性载入内存
        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

v26.13.1
// 纯 JS 极简 XML 分词器 + 树折叠。浏览器代码用 DOMParser API(同一文档模型);
// Node 无内置 XML 解析器,这里展示解析器的本质工作,notes 指向 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 流:{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; } // 声明跳过
    if (src.startsWith('</', i)) { // 结束标签
      const e = src.indexOf('>', i);
      yield { type: 'end', name: src.slice(i + 2, e) };
      i = e + 1;
      continue;
    }
    // 开始标签:<name attr="v" ...> 或 <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 层:用栈把 token 流折叠成树
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

v8.6.0
// DOM 解析:loadXML 把整棵节点树一次性载入内存;DOMDocument 提供随机访问
//(getElementsByTagName),节点操作可追加新元素
$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');          // 节点操作派:create + setAttribute + append
$third->setAttribute('id', 'bk103');
$third->setAttribute('lang', 'go');
$t = $doc->createElement('title');
$t->appendChild($doc->createTextNode('Go in Practice')); // 文本也是节点
$third->appendChild($t);
$doc->documentElement->appendChild($third);    // 挂到根元素 catalog 下
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

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 解析:parseString 把整棵节点树一次性载入内存(minidom 是标准库的 DOM 对应物)
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"))  # 文本也是节点
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

v1.99.1
// Rust 的 quick-xml 是事件(拉取)解析器而非 DOM:把 token 流折叠成自己的树,
// 或随事件到来逐个处理(模型不同)
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,
            _ => {}
        }
    }
    // 「DOM 操作」的等价物:把新书 push 进 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

v26.13.1
// 与 JavaScript 块相同的分词器 + 树折叠,带类型。浏览器代码用 DOMParser;
// Node 无内置 XML 解析器(第三方库见 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 层:用栈把 token 流折叠成树
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

语言差异说明

XML 三派同台:DOM 派(本条,整树进内存、随机访问、可回写)vs 对象派(SimpleXML/ElementTree,见 simplexml)vs 流式派(XMLReader/SAX/iterparse,见 xmlreader_writer)——大文件与内存敏感场景选流式,复杂查询与改写选 DOM。

PHP:DOMDocument 是标准扩展(libxml2 内核);getElementsByTagName 返回「活」的 DOMNodeList(append 后 length 立即变化);loadXML 收字符串、load 收文件;格式化输出靠 formatOutput=true。

C:stdlib 无 XML——示例手写极简扫描器(元素/属性/文本三层,~80 行);生产用 libxml2(xmlReadMemory/tree)。

C++:同 C 手写扫描器;生产用 libxml2、pugixml(DOM 派)。

C#:XmlDocument 是 DOM 派(SelectNodes 支持 XPath);同族 LINQ to XML(XDocument)见 simplexml。

Go:encoding/xml 无 DOM——结构体映射派(Unmarshal 解码到类型化值),模型不同但线上格式相同;需要真 DOM 时第三方 xmlpath。

Java:javax.xml.parsers DOM(W3C DOM 标准 API);XPath 用 javax.xml.xpath。

JavaScript:浏览器 DOMParser 是标准 XML DOM API(DOM 派);Node 无内置 XML 解析器——示例手写分词器 + 栈折叠演示 DOM 构建本质,生产用 xmldom/fast-xml-parser。

Python:xml.dom.minidom 是标准库 DOM 对应物(getElementsBy* 同名 API);更常用的对象派是 ElementTree(见 simplexml)。

Rust:stdlib 无 XML——quick-xml 是事件(拉取)解析器(模型不同:折叠 token 流成自己的树);DOM 派第三方 minidom/roxmltree。

TypeScript:同 JavaScript。