第一:我是新求职者。使用python..so请帮帮我。我正在尝试使用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'
提前致谢
答案 0 :(得分: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'
答案 1 :(得分: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']