XML DOM 遍历节点树

XML DOM 遍历节点树 最全最实用攻略(2025 版)

—— 5 种方法吃透,背会前 3 种就打遍天下!

推荐指数排行榜(直接看这个就够)

排名遍历方式推荐指数适用场景一句话评价
1for…of + element.children★★★★★99% 项目(只关心元素节点)最现代、最清晰、最推荐
2querySelectorAll 一把梭★★★★★已知要找什么标签,直接干就行能用它就别手写遍历
3递归函数(深度优先 DFS)★★★★打印整棵树、复杂处理经典必会
4childNodes + 过滤空白★★★★必须处理文本节点、注释时老项目常见
5nextElementSibling 横向遍历★★★★同层兄弟节点很多时(比如 1000 本书)性能最高

真实 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>

5 种遍历写法完整代码(直接复制)

const doc = new DOMParser().parseFromString(xmlStr, "text/xml");
const root = doc.documentElement;  // <bookstore>

1. 终极推荐:children + for…of(99% 项目都用这个)

function traverse1(node) {
  console.log(node.tagName);                 // 只打印元素
  for (const child of node.children) {       // 自动跳过空白文本!
    traverse1(child);
  }
}
traverse1(root);

2. 懒人福音:querySelectorAll 一把抓(能用就别手写遍历)

// 所有书
root.querySelectorAll("book").forEach(book => {
  console.log(book.getAttribute("id"), book.querySelector("title")?.textContent);
});

// 所有标题
root.querySelectorAll("title").forEach(t => console.log(t.textContent));

// 所有属性为 lang="zh" 的节点
root.querySelectorAll("[lang='zh']").forEach(n => console.log(n.tagName));

3. 经典递归(打印整棵树,必会!)

function walk(node, depth = 0) {
  const indent = "  ".repeat(depth);
  let info = node.nodeName;

  if (node.nodeType === 1) {                    // 元素
    if (node.attributes.length > 0) {
      info += ` [${[...node.attributes].map(a => `${a.name}="${a.value}"`).join(" ")}]`;
    }
  } else if (node.nodeType === 3) {             // 文本
    const text = node.nodeValue.trim();
    if (text) info += ` → "${text}"`;
    else return;                                // 跳过空白文本
  } else if (node.nodeType === 8) {             // 注释
    info += ` → <!-- ${node.nodeValue.trim()} -->`;
  }

  console.log(indent + info);

  for (const child of node.childNodes) {
    walk(child, depth + 1);
  }
}

walk(doc);   // 从文档根开始

输出(超级清晰):

#document
  xml
  bookstore
    <!-- 热门图书 -->
    book [id="1" category="编程"]
      title [lang="zh"] → "JavaScript 高级程序设计"
      author → "扎卡斯"
      price → "99.00"
    book [id="2" category="科幻"]
      title [lang="zh"] → "三体"
      author → "刘慈欣"

4. childNodes + 过滤空白(老项目常见)

function traverse4(node) {
  for (const child of node.childNodes) {
    if (child.nodeType === 1) {                 // 只处理元素节点
      console.log(child.tagName);
      traverse4(child);
    }
    // 如果需要处理注释或非空文本,再加判断
  }
}

5. 横向遍历兄弟节点(性能最高,适合大数据量)

// 遍历所有 <book>(即使有 10000 本也丝滑)
let book = root.firstElementChild;
while (book) {
  console.log(book.getAttribute("id"), book.querySelector("title")?.textContent);
  book = book.nextElementSibling;
}

终极选择指南(一表搞定)

你想干啥?直接用这个写法
只遍历元素节点for (const child of node.children)
想要整棵树结构打印出来上面第 3 种递归 walk()
已知标签名,想快速拿到所有querySelectorAll("tagname")
同层节点超多(>1000)firstElementChild + nextElementSibling
必须处理文本节点、注释childNodes + node.nodeType 判断
想用 map/filter/reduce[...node.children]Array.from()

一句话总结(背下来就无敌)

2025 年写 XML DOM 遍历,永远记住这三句话:

  1. 能用 querySelectorAll 就别手写遍历
  2. 手写遍历一律用 for…of + node.children
  3. 想看完整树结构就用递归 walk()

掌握了这 3 点 + 上面的 5 种代码模板,
你就已经达到了 XML DOM 遍历的“宗师”级别!

需要我给你一个「实时可视化节点树遍历演示网页」(点哪里就高亮路径),随时说一声~

文章已创建 2732

发表回复

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

相关文章

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

返回顶部