XML DOM 浏览器差异
剖析早期浏览器在解析 XML 空白字符与换行时的历史差异(旧版 IE 忽略空白文本节点导致 childNodes 为 4,而遵循 W3C 规范的浏览器保留空白文本节点导致 childNodes 为 9),并给出跨浏览器一致处理方案。
学完这一章,你能够
- 剖析早期浏览器在解析 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)的计数差异
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`childNodes.length` 等于 `9`(包含首尾及相邻元素间的 5 个空白文本节点),而 `children.length` 只统计元素子节点,因此恒等于 `4`。