XML DOM – 导航节点

XML DOM 导航节点 最全速查表(2025 版)

—— 一张图 + 12 行代码吃透所有上下左右移动!

1. 终极导航属性一览表(背会这 10 个就无敌)

方向老属性(兼容 IE11)现代推荐属性(2025 首选)是否跳过空白文本节点必背度
父节点node.parentNodenode.parentNode★★★★★
第一个子节点node.firstChild(常是换行)node.firstElementChild(推荐)★★★★★
最后一个子节点node.lastChild(常是换行)node.lastElementChild(推荐)★★★★★
上一个兄弟node.previousSibling(常是换行)node.previousElementSibling(推荐)★★★★★
下一个兄弟node.nextSibling(常是换行)node.nextElementSibling(推荐)★★★★★
所有子元素node.childNodes(含空白)node.children(只元素,强烈推荐)★★★★★

2025 年铁律:永远优先使用带 Element 的版本(自动跳过换行/空格文本节点)!

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

3. 12 行代码演示全部导航(直接复制运行)

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

// 1. 取第一本书(推荐写法)
const firstBook = root.firstElementChild;          // 直接跳过注释和换行!

// 2. 取最后一本书
const lastBook  = root.lastElementChild;

// 3. 从第一本书开始横向遍历所有书(最常用!)
let current = root.firstElementChild;
while (current) {
  console.log(
    current.getAttribute("id"),
    current.querySelector("title")?.textContent
  );
  current = current.nextElementSibling;           // 关键导航!
}

// 4. 向上找到父节点(常用于事件委托)
const title = doc.querySelector("title");
console.log(title.parentNode.tagName);             // "book"
console.log(title.parentNode.parentNode.tagName);  // "bookstore"

// 5. 从任意节点回到根
let node = doc.querySelector("price");
while (node.parentNode) {
  if (node.tagName === "bookstore") {
    console.log("已回到根节点");
    break;
  }
  node = node.parentNode;
}

4. 经典导航场景速查表

你想干啥?一行代码搞定(2025 推荐)
取第一本/最后一个书root.firstElementChild / root.lastElementChild
取上一本/下一本书book.previousElementSibling / book.nextElementSibling
取当前书的父节点(book)title.parentNode
取当前书的爷爷节点(bookstore)title.parentNode.parentNode
从任意节点一直往上到根while(node.parentNode) node = node.parentNode
取某书的所有子元素(title/author…)book.children
安全取第一个子元素(防 null)book.firstElementChild || null
循环处理所有同级 bookfor(let b=root.firstElementChild; b; b=b.nextElementSibling)

5. 常见坑 & 终极解决方案

错误写法正确写法(2025)
firstChild 拿到换行文本节点node.firstChildnode.firstElementChild
previousSibling 拿到注释或空白node.previousSiblingnode.previousElementSibling
遍历时漏掉最后一本书for(;;) 写错条件用 while + nextElementSibling(最保险)
parentNode 在根节点上返回 null 崩溃直接 node.parentNode.parentNode先判断 if (node.parentNode)
想取所有子节点但包含一堆空白node.childNodes.forEachfor (const c of node.children)

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

2025 年写 XML DOM 导航,只记住这一句话:
所有导航一律加 Element!
firstElementChildlastElementChildnextElementSiblingpreviousElementSiblingchildrenparentNode

只要看到不带 Element 的导航属性,全部替换成带 Element 的版本,99% 的坑瞬间消失!

需要我给你一个「XML DOM 节点导航可视化小工具」(点哪个节点就高亮它的 parent/children/sibling),随时说一声~

文章已创建 2732

发表回复

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

相关文章

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

返回顶部