为什么 dom.firstChild.firstChild.nodeValue 打印根标签内的文本?

Why does dom.firstChild.firstChild.nodeValue print the text inside the root tag?

library.xml

<?xml version="1.0" encoding="utf-8"?>
<library>library-text. :D
    <book isbn="1111111111">
        <title lang="en">T1 T1 T1 T1 T1</title>
        <date>2001</date>
        <author>A1 A1 A1 A1 A1</author>     
        <price>10.00</price>
    </book>
    <book isbn="2222222222">
        <title lang="en">T2 T2 T2 T2 T2</title>
        <date>2002</date>
        <author>A2 A2 A2 A2 A2</author>     
        <price>20.00</price>
    </book>
    <book isbn="3333333333">
        <title lang="en">T3 T3 T3 T3</title>
        <date>2003</date>
        <author>A3 A3 A3 A3 A3y</author>        
        <price>30.00</price>
    </book>
</library>

Python代码

import xml.dom.minidom as minidom

xml_fname = "library.xml"

dom = minidom.parse(xml_fname) 

print(dom.firstChild.tagName)
print(dom.firstChild.firstChild.nodeValue)

输出

library
library-text. :D

为什么 dom.firstChild.firstChild.nodeValue 打印根标签内的文本?

不应该是dom.firstChild.nodeValue吗?

DOM中的节点不仅代表元素,文本值也是也是节点。 <library> 元素中的第一个子节点是一个文本节点,它的值是 Python 字符串 'library-text. :D\n ':

>>> dom.firstChild.firstChild
<DOM Text node "'library-te'...">
>>> dom.firstChild.firstChild.nodeValue
'library-text. :D\n    '

注意 Elements 的 nodeValue 属性 总是 null (== None in Python);请参阅 DOM level 1 definition for Node:

In cases where there is no obvious mapping of these attributes for a specific nodeType (e.g., nodeValue for an Element or attributes for a Comment), this returns null.

Definition Group NodeType section.

中指定了 Node.nodeValue 的什么类型的节点类型。

DOMAPI是一个非常基本的框架,基本API,旨在与非常广泛的语言兼容,对于 DOM 级别 1 规范(minidom 支持的唯一规范)尤其如此。如果可以避免,您通常根本不想使用它。在 Python 中,使用更高级别的 API,如 ElementTree API (use the lxml library,这是一个功能更丰富的兼容实现。

使用 ElementTree,您主要处理 只是 元素,并且可以通过元素上的 texttail 属性访问文本。