首页 > 解决方案 > 带有重复标签名称的 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")

标签: pythonxmlelementtree

解决方案


推荐阅读