[英]Reading xml file and printing using python
First : am a new beg. 第一:是一个新的乞求。 using python..so please help me out.I'm trying to read a XML file using Python.
使用python..so,请帮帮我。我正在尝试使用Python读取XML文件。 My xml file name is rgpost.xml
我的xml文件名为rgpost.xml
<volume name="sp" type="span" operation="create">
<driver>HDD1</driver>
</volume>
My code : 我的代码:
import xml.etree.ElementTree as ET
doc = ET.parse("rgpost.xml")
s = doc.find("volume")
print s.attrib["name"]
While running this am getting error : 运行时出现错误:
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'
Thanks in advance 提前致谢
Life is much easier if you get the root: 如果您扎根,生活会容易得多:
>>> 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'
volume
is considered the root of the XML tree, so what you want is effectively doc.attrib['name']
. 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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.