带有重复标签名称的Python XML解析

时间:2018-07-17 18:28:58

标签: python xml elementtree

我正在将Python 2.7x与ElementTree一起使用。 我对XML解析非常陌生,在获取名称为'status'的第二个标签的文本值时遇到了一些麻烦。

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>

我需要找到第一个子代'status'标记,并确认其Text值为= 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>标记获取Text值。

我使用的是'findall',但使用子标记,并尝试将级别设置为<teststatus>,但是似乎找不到子值'status':

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")

0 个答案:

没有答案