问题描述
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 中的节点不仅代表元素,文本值也是 节点。 return jsonResponse
.record
.map((products) => new ProductsModel.fromJson(products))
.toList();
元素内的第一个子节点是一个文本节点,它的值是 Python 字符串 <library>
:
'library-text. :D\n '
请注意,>>> dom.firstChild.firstChild
<DOM Text node "'library-te'...">
>>> dom.firstChild.firstChild.nodeValue
'library-text. :D\n '
s 的 nodeValue
属性总是 null(== Element
在 Python 中);见DOM level 1 definition for Node
:
如果这些属性对于特定的 None
没有明显的映射(例如,nodeType
代表 nodeValue
或 Element
代表 attributes
),这将返回 Comment
。
在 Definition Group NodeType section 中指定了哪种节点类型保存了 null
的哪种类型的值。
DOM API 是一个非常基本的 API,旨在与非常广泛的语言兼容,这对于 DOM Level 1 规范(唯一的规范{ {1}} 支持)。如果可以避免的话,您通常根本不想使用它。在 Python 中,使用更高级别的 API,例如 ElementTree API(使用 lxml
library,这是一种功能更丰富的兼容实现)。
使用 ElementTree,您主要处理只 元素,文本可通过元素上的 Node.nodeValue
和 minidom
属性访问。