0

第一:我是一个新的乞求。使用 python ..所以请帮帮我。我正在尝试使用 Python 读取 XML 文件。我的 xml 文件名是 rgpost.xml

<volume name="sp" type="span" operation="create">
    <driver>HDD1</driver>
</volume>

我的代码:

import xml.etree.ElementTree as ET
doc = ET.parse("rgpost.xml")
s = doc.find("volume")
print s.attrib["name"]

运行此程序时出现错误:

sp:~# python volume_check.py volume  
Traceback (most recent call last):  
  File "volume_check.py", line 13, in <module>  
    print s.attrib["name"]  
AttributeError: 'NoneType' object has no attribute 'attrib'

提前致谢

4

2 回答 2

3

如果你得到了根,生活会容易得多:

>>> import xml.etree.ElementTree as ET
>>> doc = ET.parse("rgpost.xml")
>>> root = doc.getroot() # <--- this is the new line
>>> root
<Element 'volume' at 0x1004d8f10>
>>> root.keys()
['operation', 'type', 'name']
>>> root.attrib["name"]
'sp'
>>> root.get("name")
'sp'
于 2012-10-21T12:39:49.207 回答
1

volume被认为是 XML 树的根,所以你想要的是有效的doc.attrib['name'].

xml="""<volume name="sp" type="span" operation="create">
    <driver>HDD1</driver>
</volume>"""

import xml.etree.ElementTree as ET
doc = ET.fromstring(xml)
print doc
# <Element 'volume' at 0x26f1d50>
print doc.attrib['name']
于 2012-10-21T12:29:29.777 回答