xml - 使用python从xml文件中读取某些信息
问题描述
我是python新手,xml
对python有一点经验。我正在尝试使用 python 的xml.etree.ElementTree
模块来解析xml
文件。使用print(info.text)
,它可以打印出xml
文件中的所有元素,例如WIL-RT2
,Rtr_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)
解决方案
有获取文本的方法。这是代码 print(info.findtext("[@id='0x1006e']"))
推荐阅读
- excel - 使用 openpyxl 从多个工作表中创建一个主重复的名称列表
- c# - 如何在 C# 中读取多个 zip 文件
- multithreading - 向量(或向量的向量)上的并发操作
- python - 如何在 python 中回复内联键盘标记
- excel - 根据特定条件自动平均分配任务
- javascript - 缩小失败。返回未缩小的内容。Javascript
- unix - 如果模式在任何顺序行中的两列之间重复,则比较两行并仅打印一个
- json - 颤振错误:预期类型为“FutureOr”的值
- >',但得到了“_JsonMap”类型之一
- javascript - 提交表单后如何阻止选择标签重置为默认值?
- .htaccess - .htaccess RewriteRule 用于导航