蓝色天空网mbsky.com · 知识 · 实践 · 创造XML DOM · 本地阅读预览
教程 / XML / Web Service / XML DOM

XML DOM 浏览器差异

剖析早期浏览器在解析 XML 空白字符与换行时的历史差异(旧版 IE 忽略空白文本节点导致 childNodes 为 4,而遵循 W3C 规范的浏览器保留空白文本节点导致 childNodes 为 9),并给出跨浏览器一致处理方案。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

DOM 解析中的空白与换行处理差异

虽然所有现代浏览器均遵循 W3C DOM 规范,但在早期浏览器演进史中,不同内核在 XML 解析细节上存在一项极其关键的差异:如何处理元素标签之间的空白字符和换行符。

使用记事本或代码编辑器编写 XML 时,几乎都会在标签之间插入换行符(CR/LF)和缩进空格(例如每行前加两个空格)。历史上的旧版 Internet Explorer(IE8 及更早的 MSXML 默认解析行为)会自动忽略元素之间仅含空白与换行的文本,不生成文本节点;而 Firefox、Chrome、Safari、Edge 以及 IE9+ 等遵循 W3C 标准的解析器则会严格保留这些空白并把它们解析为文本节点(`nodeType === 3`)。

childNodes 计数差异(4 vs 9)与现代一致写法

对带缩进的 `books.xml` 执行 `x = xmlDoc.documentElement.childNodes` 并输出 `x.length` 时,这种差异会直接显现:忽略空白文本节点的旧版 IE 会返回 `4`(仅计入 4 个 `<book>` 元素);而遵循 W3C DOM 标准的浏览器(以及 Python `xml.dom.minidom`)会返回 `9`(4 个 `<book>` 元素外加前后与元素之间的 5 个空白文本节点)。为彻底消除差异,传统做法是在遍历 `childNodes` 时显式判断 `nodeType === 1`,而现代浏览器 DOM 更推荐使用只包含元素子节点的 `documentElement.children`(其 `length` 恒为 `4`)。

实测 W3C 保留空白文本节点(9)与元素过滤/去空白解析(4)的计数差异

python · 阅读源码
"""Offline XML DOM verification lab for Chapter 12 (mozilla-vs-ie)."""
import json
import sys
import xml.dom.minidom as minidom
from lxml import etree

VERSION = f"CPython {sys.version.split()[0]} + xml.dom.minidom + lxml {etree.__version__}"

BOOKS_XML = """<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
    <book category="cooking">
        <title lang="en">Everyday Italian</title>
        <author>Giada De Laurentiis</author>
        <year>2005</year>
        <price>30.00</price>
    </book>
    <book category="children">
        <title lang="en">Harry Potter</title>
        <author>J K. Rowling</author>
        <year>2005</year>
        <price>29.99</price>
    </book>
    <book category="web">
        <title lang="en">XQuery Kick Start</title>
        <author>James McGovern</author>
        <year>2003</year>
        <price>49.99</price>
    </book>
    <book category="web" cover="paperback">
        <title lang="en">Learning XML</title>
        <author>Erik T. Ray</author>
        <year>2003</year>
        <price>39.95</price>
    </book>
</bookstore>"""

BOOK_CRLF_XML = (
    "<book>\r\n"
    "  <title>Everyday Italian</title>\r\n"
    "  <author>Giada De Laurentiis</author>\r\n"
    "  <year>2005</year>\r\n"
    "  <price>30.00</price>\r\n"
    "</book>"
)


def case_w3c_preserves_whitespace_text_nodes():
    doc = minidom.parseString(BOOKS_XML)
    children = doc.documentElement.childNodes
    node_types = [n.nodeType for n in children]
    expected = {
        "total_child_nodes": 9,
        "element_nodes": 4,
        "whitespace_text_nodes": 5,
        "type_sequence": [3, 1, 3, 1, 3, 1, 3, 1, 3],
    }
    actual = {
        "total_child_nodes": len(children),
        "element_nodes": sum(1 for t in node_types if t == 1),
        "whitespace_text_nodes": sum(1 for t in node_types if t == 3),
        "type_sequence": node_types,
    }
    return {
        "name": "w3c_preserves_whitespace_text_nodes",
        "summary": "验证遵循 W3C DOM 规范的解析器保留缩进与换行空白文本节点,4 本书的 bookstore 共有 9 个 childNodes",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_legacy_ie_vs_element_only_count():
    doc = minidom.parseString(BOOKS_XML)
    elem_only = [n for n in doc.documentElement.childNodes if n.nodeType == 1]
    parser = etree.XMLParser(remove_blank_text=True)
    lxml_root = etree.fromstring(BOOKS_XML.encode("utf-8"), parser=parser)
    expected = {
        "element_only_count": 4,
        "lxml_stripped_child_count": 4,
        "matches_legacy_ie_and_modern_children": True,
    }
    actual = {
        "element_only_count": len(elem_only),
        "lxml_stripped_child_count": len(lxml_root),
        "matches_legacy_ie_and_modern_children": len(elem_only) == len(lxml_root) == 4,
    }
    return {
        "name": "legacy_ie_vs_element_only_count",
        "summary": "对比按 nodeType==1 过滤及 lxml remove_blank_text=True 的结果(均为 4),对应旧版 IE 与现代 element.children",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_indented_book_crlf_whitespace_nodes():
    doc = minidom.parseString(BOOK_CRLF_XML)
    children = doc.documentElement.childNodes
    elem_names = [n.tagName for n in children if n.nodeType == 1]
    expected = {
        "raw_child_nodes": 9,
        "element_children": ["title", "author", "year", "price"],
        "first_child_is_text_node": True,
    }
    actual = {
        "raw_child_nodes": len(children),
        "element_children": elem_names,
        "first_child_is_text_node": children[0].nodeType == 3,
    }
    return {
        "name": "indented_book_crlf_whitespace_nodes",
        "summary": "解析含 CRLF 换行与两空格缩进的 book 示例,验证其原始子节点数为 9 而元素子节点为 4",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_compact_xml_zero_whitespace_nodes():
    compact = "<bookstore><book/><book/><book/><book/></bookstore>"
    doc = minidom.parseString(compact)
    expected = {"child_count": 4, "all_elements": True}
    actual = {
        "child_count": len(doc.documentElement.childNodes),
        "all_elements": all(n.nodeType == 1 for n in doc.documentElement.childNodes),
    }
    return {
        "name": "compact_xml_zero_whitespace_nodes",
        "summary": "验证紧凑无空白 XML 在 W3C DOM 解析器中不产生空白文本节点,childNodes 数量直接等于 4",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_w3c_preserves_whitespace_text_nodes(),
        case_legacy_ie_vs_element_only_count(),
        case_indented_book_crlf_whitespace_nodes(),
        case_compact_xml_zero_whitespace_nodes(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 确认缩进 books.xml 在 minidom 中 documentElement.childNodes 长度为 9(5 空白文本 + 4 元素),而按 nodeType==1 过滤或 lxml remove_blank_text=True 均为 4。
实测 W3C 保留空白文本节点(9)与元素过滤/去空白解析(4)的计数差异

所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。

当前源码 SHA256:28eccff83ba8a0bd3ba9416fa5a77268d13e76df3c03f2798e51e98d1979a2c6

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载XML DOM 浏览器差异实验

所需环境:Windows x64、CPython 3.12.14(xml.dom.minidom + lxml 6.1.3)离线 XML DOM 验证环境。

ZIP SHA256:91cf7d5905e42a5cd31480a20350b62ad0fdbe11e553ac09cbbdd63aa7a6c1f1

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在现代浏览器中解析带换行缩进、包含 4 个 `<book>` 子元素的 `<bookstore>` 时,`documentElement.childNodes.length` 与 `documentElement.children.length` 分别等于多少?

展开参考解答

`childNodes.length` 等于 `9`(包含首尾及相邻元素间的 5 个空白文本节点),而 `children.length` 只统计元素子节点,因此恒等于 `4`。

规范与官方依据