XML DOM 访问节点 最全最实用速查表(2025 版)
—— 按真实使用频率排序,背会前 8 行就够你打遍天下
| 排名 | 访问方式 | 返回值 | 适用场景 | 推荐指数 |
|---|---|---|---|---|
| 1 | element.textContent | string | 取标签内所有纯文本(最常用!) | ★★★★★ |
| 2 | element.getAttribute("name") | string | null | 取属性值 | ★★★★★ |
| 3 | element.setAttribute("name", "value") | void | 设置/修改属性 | ★★★★★ |
| 4 | doc.querySelector("css选择器") | Element | null | 用 CSS 选择器精确取一个节点(现代首选) | ★★★★★ |
| 5 | doc.querySelectorAll("css选择器") | NodeList | 用 CSS 选择器取多个节点 | ★★★★★ |
| 6 | doc.getElementsByTagName("tag") | HTMLCollection (live) | 取所有同名标签(经典老方法) | ★★★★ |
| 7 | element.children | HTMLCollection | 取所有“亲儿子”元素(自动跳过空白文本) | ★★★★★ |
| 8 | element.firstElementChild / lastElementChild | Element | null | 取第一个/最后一个元素子节点(跳过空白) | ★★★★★ |
| 9 | node.parentNode | Node | 取父节点 | ★★★★ |
| 10 | node.previousElementSibling / nextElementSibling | Element | null | 取上一个/下一个兄弟元素(跳过空白) | ★★★★★ |
真实 XML 示例(全程用这一个)
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book id="1" category="编程">
<title lang="zh">JavaScript 高级程序设计</title>
<author>扎卡斯</author>
<price>99.00</price>
</book>
<book id="2" category="科幻">
<title lang="zh">三体</title>
<author>刘慈欣</author>
</book>
</bookstore>
实战代码(JavaScript,最常用语言)
const parser = new DOMParser();
const doc = parser.parseFromString(xmlStr, "text/xml");
const root = doc.documentElement; // <bookstore>
// 1. 取所有书(两种写法都行)
const books1 = root.getElementsByTagName("book"); // 老派
const books2 = root.querySelectorAll("book"); // 新派(推荐)
// 2. 遍历所有书(推荐写法)
for (const book of books2) {
const id = book.getAttribute("id"); // "1"
const category = book.getAttribute("category"); // "编程"
const title = book.querySelector("title")?.textContent; // "JavaScript 高级程序设计"
const lang = book.querySelector("title")?.getAttribute("lang"); // "zh"
const author = book.querySelector("author")?.textContent;
const price = book.querySelector("price")?.textContent;
console.log(`${id}. 《${title}》 ${author} [${category}] ¥${price}`);
}
终极选择器对比表(一图看懂选哪个)
| 需求 | 最佳写法(2025 推荐) | 备选(老项目) |
|---|---|---|
| 取第一本书 | root.querySelector("book") | root.getElementsByTagName("book")[0] |
| 取 id=2 的书 | doc.querySelector("book[id='2']") | 循环 + getAttribute |
| 取所有中文书 | root.querySelectorAll("title[lang='zh']") | 循环判断 |
| 取某本书的标题文本 | book.querySelector("title")?.textContent | book.getElementsByTagName("title")[0].firstChild.nodeValue |
| 取 category=”科幻” 的书 | root.querySelector("book[category='科幻']") | 循环 |
| 取所有价格大于 50 的书 | 只能循环 + parseFloat(price) > 50 | 同左 |
| 取根元素 | doc.documentElement | 同左 |
99% 项目只需要记住这 5 行代码
// 1. 加载
const doc = new DOMParser().parseFromString(xmlStr, "text/xml");
// 2. 取根
const root = doc.documentElement;
// 3. 取单个节点(推荐)
const node = root.querySelector("选择器");
// 4. 取多个节点(推荐)
const nodes = root.querySelectorAll("选择器");
// 5. 取文本 / 属性
const text = node.textContent;
const attr = node.getAttribute("name");
背会上面 5 行 + 上面的选择器表,
你就已经超越了 95% 的前端/后端开发者对 XML DOM 的掌握程度!
需要我给你生成一个「XML DOM 访问节点交互式练习网页」或「PDF 口袋书」,随时说一声~