python - 带有重复标签名称的 Python XML 解析
问题描述
我将 python 2.7x 与 ElementTree 一起使用。我对 XML 解析非常陌生,在获取名为“状态”的第二个标签的文本值时遇到了一些麻烦。
XML 的结构如下:
<?xml version="1.0" ?>
<result>
<teststatus>
<test_id>Read_44</test_id>
<pass_ios>0</pass_ios>
<seek_type>Sequential</seek_type>
<multipath_mode>0</multipath_mode>
<start_time>Jul 16 11:13:24</start_time>
<end_time>Jul 16 11:14:52</end_time>
<test_time>00:01:28</test_time>
<test_ios>1572864</test_ios>
<test_bytes>6442450944</test_bytes>
<test_errors>0</test_errors>
<test_read_errors>0</test_read_errors>
<test_write_errors>0</test_write_errors>
<test_compare_errors>0</test_compare_errors>
<num_test_luns>1</num_test_luns>
<luns xmlns:xlink="http://www.w3.org/1999/xlink">
<port>10</port>
<target>0</target>
<lun_id>0</lun_id>
<status>Passed</status> <-- Current State of the Test
<ios_done>1572864</ios_done>
<bytes_done>6442450944</bytes_done>
<errors>83011124</errors>
<threads_done>0</threads_done>
</lun></luns>
</teststatus>
<status>0</status> <------ XML Test Status Request Succeeded
</result>
我需要找到第一个孩子的“状态”标签并确认它的文本值为 = 0,并且可以使用以下代码正常工作:
root = ET.fromstring(commandResponseXML)
for child in root:
print(child.tag, child.text)
if ( child.text == '0' and child.tag == 'status' ):
----Do things here
我的问题是<status>
从<teststatus>
.
我正在使用“findall”,但子标签并试图将级别“设置”为<teststatus>
但似乎从未找到生成的子值“状态”:
for testStatusResponse in root.findall('.//teststatus'):
for newchild in testStatusResponse:
if newchild.tag == "status":
testState = testStatusResponse.text
s = "---The updated Test State is " + str(testState)
print s
openOutput.write(s + "\n")
解决方案
推荐阅读
- ios - 未找到 SocketRocket/SocketRocket.h' 文件
- google-cloud-platform - 将 IAM 角色分配给 GSuite 管理控制台组
- php - 如何在cakephp3中获取控制器中所有方法的列表
- regex - 正则表达式用相对路径查找和替换 ES6 裸模块
- sql - 关系数据库设计是否适合存储这种复杂结构
- servicestack - 使用 ServiceStack 的 Funq 解决依赖关系
- css - 在 .Net Core 中如何重写环境的图像路径?
- python - Matplotlib pyplot:是否有可能有指数轴?
- hibernate - @Embeddable 与 @ManyToOne Hibernate 和 CascadeType.ALL
- android - React Native 在应用内发送短信