首页 > 解决方案 > 使用python从xml文件中读取某些信息

问题描述

我是python新手,xml对python有一点经验。我正在尝试使用 python 的xml.etree.ElementTree模块来解析xml文件。使用print(info.text),它可以打印出xml文件中的所有元素,例如WIL-RT2Rtr_Cisco...,但我只想检索WIL-RT2然后基于WIL-RT2,我可以返回Rtr_Cisco. 这是我的xml文件的一部分:

<?xml version="1.0" encoding="ISO-8859-1"?>
<model-response-list xmlns="http://www.ca.com/spectrum/restful/schema/response" total-models="115" throttle="115" error="EndOfResults">
<model-responses>
<model mh="0x700e8f">
<attribute id="0x1006e">WIL-RT2</attribute>
<attribute id="0x10000">Rtr_Cisco</attribute>
<attribute id="0x12d7f">172.20.111.252</attribute>
<attribute id="0x12bfb">NAT,192.168.249.150</attribute>
<attribute id="0x100ae" error="NoSuchAttribute"/>
<attribute id="0x100af" error="NoSuchAttribute"/>
</model>
</model-responses>
</model-response-list>

这是我的python代码

for item in root.findall("{http://www.ca.com/spectrum/restful/schema/response}model-responses"):
     #print(item.findall('{http://www.ca.com/spectrum/restful/schema/response}model'))
     for child in item.findall('{http://www.ca.com/spectrum/restful/schema/response}model'):
         #print(child.attrib, child.tag)
         for info in child.findall('{http://www.ca.com/spectrum/restful/schema/response}attribute'):
               print(info.tag, info.attrib)
               print(info.text)

标签: xmlpython-3.xelementtree

解决方案


有获取文本的方法。这是代码 print(info.findtext("[@id='0x1006e']"))


推荐阅读