如何用Python解析XML文件?
我想要打印出一个xml文件里的所有元素和属性。这个xml文件的内容是:
<topology>
<switch id="10">
<port no="1">h1</port>
<port no="2">h2</port>
</switch>
<tunnel id="91">
<port no="1">s1</port>
<port no="8">s8</port>
</tunnel>
</topology>
我该怎么做呢?另外,我怎么才能在拓扑中找到像“switch”这样的元素呢?
2 个回答
4
这是我能正常运行的代码:
import xml.etree.ElementTree as ET
doc = ET.parse("nm.xml")
s = doc.find("switch")
print s.attrib["id"]
for item in s:
print item.attrib["no"]
print item.text
t = doc.find("tunnel")
print t.attrib["dpid"]
for item in t:
print item.attrib["no"]
print item.text
附注:你可以把 ET.parse 替换成 ET.fromstring,然后把输入的参数改成字符串类型,这样也能正常工作。
4
正如S.Lott所说,你有太多方法可以解决这个问题,
这里有一个使用 lxml的例子,
from lxml import etree
xml_snippet = '''<topology>
<switch id="10">
<port no="1">h1</port>
<port no="2">h2</port>
</switch>
<tunnel dpid="91">
<port no="1">s1</port>
<port no="8">s8</port>
</tunnel>
</topology>'''
root = etree.fromstring(xml_snippet)
for element in root.iter("*"):
print element.tag, element.items()
输出结果:
topology []
switch [('id', '10')]
port [('no', '1')]
port [('no', '2')]
tunnel [('dpid', '91')]
port [('no', '1')]
port [('no', '8')]
使用XPath查找属性
attribute = '10'
element = root.find('.//switch[@id="%s"]' % attribute)
element.items()
输出结果:
[('id', '10')]