【发布时间】:2016-12-21 00:37:34
【问题描述】:
我已经尝试解析一些 XML 几个小时了,但没有成功。检查了类似的线程并查看了 ElementTree 文档,但仍然很迷茫。
基本上,我从一个存储在字符串中的路由器接收一些 XML 输出,而我必须依次解析一些特定信息。
这是我正在处理的 xml 示例:
xml = """<rpc-reply xmlns:junos="http://xml.juniper.net/junos/14.1D0/junos">
<route-information xmlns="http://xml.juniper.net/junos/14.1D0/junos-routing">
<!-- keepalive -->
<route-table>
<table-name>inet.0</table-name>
<destination-count>52</destination-count>
<total-route-count>52</total-route-count>
<active-route-count>52</active-route-count>
<holddown-route-count>0</holddown-route-count>
<hidden-route-count>0</hidden-route-count>
<rt junos:style="brief">
<rt-destination>5.5.5.5/32</rt-destination>
<rt-entry>
<active-tag>*</active-tag>
<current-active/>
<last-active/>
<protocol-name>Direct</protocol-name>
<preference>0</preference>
<age junos:seconds="428929">4d 23:08:49</age>
<nh>
<selected-next-hop/>
<via>lo0.0</via>
</nh>
</rt-entry>
</rt>
</route-table>
</route-information>
<cli>
<banner></banner>
</cli>
</rpc-reply>"""
例如,我想要获取/打印内容的节点是 rt-destination。
我试过了:
root = ET.fromstring(xml)
values = root.find('rt')
for element in values:
print element.text
这个,
value= root.find('rt-destination')
print value
这将在特定节点设置根(指针?),
x = root.getiterator(tag = "destination-count")
任何有关如何遍历此特定节点或如何获得所需结果的帮助将不胜感激。
【问题讨论】:
标签: python xml automation elementtree