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

2024-06-17 12:33:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: a2datetitlea1libraryxmlpricea3
1条回答
网友
1楼 · 发布于 2024-06-17 12:33:25

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

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

注意ElementnodeValue属性是总是null(=None在Python中);见DOM level 1 definition for ^{}

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.

什么节点类型保存Node.nodeValue的值的类型在Definition Group NodeType section中指定

domapi是一个非常简单的、基本的API,旨在与非常广泛的语言兼容,尤其是domlevel1规范(唯一受minidom支持的规范)。如果可以避免的话,你通常根本不想使用它。在Python中,使用更高级的API,如ElementTree API(使用^{} library,这是一个功能更丰富的兼容实现)

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

相关问题 更多 >