XML DOM – 访问节点

XML DOM 访问节点 最全最实用速查表(2025 版)

—— 按真实使用频率排序,背会前 8 行就够你打遍天下

排名访问方式返回值适用场景推荐指数
1element.textContentstring取标签内所有纯文本(最常用!)★★★★★
2element.getAttribute("name")string | null取属性值★★★★★
3element.setAttribute("name", "value")void设置/修改属性★★★★★
4doc.querySelector("css选择器")Element | null用 CSS 选择器精确取一个节点(现代首选)★★★★★
5doc.querySelectorAll("css选择器")NodeList用 CSS 选择器取多个节点★★★★★
6doc.getElementsByTagName("tag")HTMLCollection (live)取所有同名标签(经典老方法)★★★★
7element.childrenHTMLCollection取所有“亲儿子”元素(自动跳过空白文本)★★★★★
8element.firstElementChild / lastElementChildElement | null取第一个/最后一个元素子节点(跳过空白)★★★★★
9node.parentNodeNode取父节点★★★★
10node.previousElementSibling / nextElementSiblingElement | 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")?.textContentbook.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 口袋书」,随时说一声~

文章已创建 2732

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部