XML DOM – Document 对象 最全速查表(2025 版)
—— 它是整棵 DOM 树的“老祖宗”,99% 操作都从它开始!
| 项目 | 写法(2025 推荐) | 说明 + 口诀 | 必背度 |
|---|---|---|---|
| 整个 XML 文档对象 | doc(解析后得到的) | 所有节点的祖宗 | ★★★★★ |
| 根元素 | doc.documentElement | 永远是第一个真实标签(如 <bookstore>) | ★★★★★ |
| 创建元素 | doc.createElement("book") | 所有新标签都靠它生 | ★★★★★ |
| 创建文本节点 | doc.createTextNode("三体") | 所有纯文本都靠它生 | ★★★★★ |
| 创建注释 | doc.createComment("2025新版") | ★★★★ | |
| 创建 CDATA | doc.createCDATASection("<script>alert(1)</script>") | 不转义的原始内容 | ★★★ |
| 按标签名查找(老) | doc.getElementsByTagName("book") | 返回“活的”HTMLCollection | ★★★★ |
| 按 CSS 选择器查找(新) | doc.querySelector("book[id='1']") | 返回第一个匹配 | ★★★★★ |
| 按 CSS 选择器查找全部 | doc.querySelectorAll("book") | 返回静态 NodeList(2025 必写!) | ★★★★★ |
| 取 DOCTYPE | doc.doctype | 节点 | ★★ |
| 输出整个 XML 字符串 | new XMLSerializer().serializeToString(doc) | 保存文件、发送后端必用 | ★★★★★ |
| 解析错误检查 | doc.querySelector("parsererror") | 判断 XML 是否合法 | ★★★★★ |
2025 年你只需要记住这 6 行代码(打遍天下)
const doc = new DOMParser().parseFromString(xmlStr, "text/xml");
const root = doc.documentElement; // 根元素
// 创建节点(永远用 doc. 开头!)
const newBook = doc.createElement("book");
const text = doc.createTextNode("三体");
const comment = doc.createComment("科幻神作");
// 查找节点(永远用 querySelector(All)!)
const firstBook = doc.querySelector("book");
const allBooks = doc.querySelectorAll("book");
// 输出 XML(保存/发送)
const finalXML = new XMLSerializer().serializeToString(doc);
真实完整示例(从头到尾)
// 1. 解析 XML 字符串
const xmlStr = `<bookstore><book id="1"><title>JS高级</title></book></bookstore>`;
const doc = new DOMParser().parseFromString(xmlStr, "text/xml");
// 2. 检查是否解析成功(超级重要!)
if (doc.querySelector("parsererror")) {
throw new Error("XML 格式错误!");
}
// 3. 拿到根元素
const root = doc.documentElement; // <bookstore>
// 4. 创建一本新书
const newBook = doc.createElement("book");
newBook.setAttribute("id", "999");
const title = doc.createElement("title");
title.textContent = "三体Ⅲ:死神永生";
newBook.appendChild(title);
newBook.appendChild(doc.createElement("author")).textContent = "刘慈欣";
// 5. 添加到文档
root.appendChild(newBook);
// 6. 输出最终 XML
console.log(new XMLSerializer().serializeToString(doc));
2025 年终极口诀(背 4 句就无敌)
| 想干啥? | 永远只写这句! |
|---|---|
| 创建任何节点 | doc.createXxx(...) |
| 查找节点 | doc.querySelector(All)(...) |
| 取根元素 | doc.documentElement |
| 输出整个 XML | new XMLSerializer().serializeToString(doc) |
Document vs Element 终极区别(面试必考)
| 特性 | Document 对象 | Element 对象(如 ) |
|---|---|---|
| 是整棵树的根 | 是 | 不是 |
| 能 createElement | 能(只有它能) | 不能 |
| 有 documentElement | 有 | 没有 |
| querySelector 从哪里开始搜 | 从整个文档 | 从当前元素开始 |
| textContent | null | 有值 |
记住这张表 + 6 行代码 + 4 句口诀,
你就已经完全掌握了 XML DOM 中最核心的 Document 对象,
任何创建、查找、输出操作都能 5 秒写完!
需要我给你一个“一键查看 Document 对象所有方法 + 实时操作”的 Chrome 调试面板?随时说一声~