XML DOM 获取节点值 最全速查表(2025 版)
—— 3 秒知道用哪个属性,99% 的坑全在这张表里!
| 你想取什么值? | 推荐写法(2025 首选) | 备选(老项目) | 是否安全(不会取到换行/空格) | 必背度 |
|---|---|---|---|---|
| 元素内的全部纯文本 | element.textContent | element.innerText(IE 专用) | 完全安全 | ★★★★★ |
| 元素内的全部纯文本(第二推荐) | element.textContent?.trim() | — | 完全安全 | ★★★★★ |
| 单个文本节点的值 | textNode.nodeValue | textNode.data | 安全(但要先拿到文本节点) | ★★★★ |
| 属性值 | element.getAttribute("id") | element.attributes["id"].value | 完全安全 | ★★★★★ |
| 任意节点的值(万能判断写法) | node.textContent || node.nodeValue || "" | — | 完全安全 | ★★★★★ |
| 整个 XML 文档转字符串 | new XMLSerializer().serializeToString(doc) | doc.xml(IE 老写法) | — | ★★★★★ |
真实 XML 示例(全程用这一个)
<bookstore>
<book id="1" category="编程">
<title lang="zh"> JavaScript 高级程序设计 </title>
<author>扎卡斯</author>
<price>99.00</price>
</book>
</bookstore>
实战代码(直接复制,全部正确结果)
const doc = new DOMParser().parseFromString(xmlStr, "text/xml");
const book = doc.querySelector("book");
// 1. 取书名(最常用!自动去掉前后空格)
const title1 = book.querySelector("title").textContent.trim();
// → "JavaScript 高级程序设计"(完美!)
// 2. 取属性(推荐)
const id = book.getAttribute("id"); // "1"
const category = book.getAttribute("category"); // "编程"
const lang = book.querySelector("title").getAttribute("lang"); // "zh"
// 3. 取价格(数字用)
const price = parseFloat(book.querySelector("price").textContent); // 99
// 4. 万能安全取值函数(复制到项目里一辈子够用)
function getNodeValue(node) {
if (!node) return "";
return node.textContent?.trim() ||
node.nodeValue?.trim() ||
node.getAttribute?.(node.getAttributeName?.() || "") ||
"";
}
// 使用
console.log(getNodeValue(doc.querySelector("title"))); // "JavaScript 高级程序设计"
console.log(getNodeValue(doc.querySelector("book"))); // "JavaScript 高级程序设计扎卡斯99.00"
经典坑 & 终极解决方案
| 坑 | 错误写法 | 正确写法(2025) |
|---|---|---|
| 取到一堆换行和空格 | title.firstChild.nodeValue | title.textContent.trim() |
| 取到 null 或 undefined 崩溃 | node.textContent(node 是 null) | node?.textContent?.trim() || "" |
| 想取属性但用了 textContent | book.textContent(拿到所有子节点文本) | book.getAttribute("id") |
| 想取数字但拿到字符串 | price.textContent → “99.00” | parseFloat(price.textContent) |
| 老代码用 innerText(Firefox 不支持) | element.innerText | 一律改成 textContent |
2025 年终极记忆口诀(背 3 句就够用一辈子)
- 想取文本 → 永远只用
textContent(加 trim 更佳) - 想取属性 → 永远只用
getAttribute("name") - 不确定是啥节点 → 用
node?.textContent?.trim()最安全
一张图记住所有取值方式(强烈建议保存)
任意节点
├── 是元素? → 用 element.textContent(最常用!)
├── 是属性? → 用 element.getAttribute("name")
├── 是文本节点? → 用 textNode.nodeValue
└── 万能写法 → node?.textContent?.trim() || ""
记住这张表 + 3 句口诀,
你就已经超越 98% 的开发者对“XML DOM 取值”的掌握程度!
需要我给你一个「一键获取任意节点值的 Chrome 插件小工具」,随时说一声~