问题描述
<?xml version="1.0" encoding="utf-8"?>
<library attrib1="att11" attrib2="att22">
library-text
<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>
我该怎么做?
我尝试了以下代码:
import xml.dom.minidom as minidom
xml_fname = "library.xml"
dom = minidom.parse(xml_fname)
print(dom.firstChild.tagName)
print(dom.firstChild.attributes[0].value)
它给出了以下错误:
Traceback (most recent call last):
File "main.py",line 8,in <module>
print(dom.firstChild.attributes[0].value)
File "/usr/lib/python3.8/xml/dom/minidom.py",line 552,in __getitem__
return self._attrs[attname_or_tuple]
KeyError: 0
解决方法
DOM Node.attributes
对象是一个 NamedNodeMap
object,您必须使用规范中定义的接口。您不能只对它们进行索引,不支持类似 Python 的索引。
规范告诉你有一个 .length
属性和一个返回 Node 子类型的 item()
方法,这里是 Attr
objects:
>>> attributes = dom.firstChild.attributes
>>> for i in range(attributes.length):
... print(attributes.item(i))
...
<xml.dom.minidom.Attr object at 0x10e47f6d0>
<xml.dom.minidom.Attr object at 0x10e47f660>
这些 Attr
对象中的每一个都有 name
和 value
属性:
>>> for i in range(attributes.length):
... attr = attributes.item(i)
... print(f"Name: {attr.name},value: {attr.value}")
...
Name: attrib1,value: att11
Name: attrib2,value: att22
我在之前的回答中已经说过这一点,但我会在这里重申:DOM API 非常简单,根本不是 Pythonic。它的行为不像您期望的 Python 对象那样。如果您想要更 Pythonic 的东西,请使用 ElementTree API。例如,ElementTree API 元素有一个 .attrib
属性,它是一个 Python 字典。