迭代XML?

问题描述 投票:0回答:1

使用python导航XML的最简单方法是什么?

<html>
 <body>
  <soapenv:envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:body>
    <getservicebyidresponse xmlns="http://www.something.com/soa/2.0/SRIManagement">
     <code xmlns="">
      0
     </code>
     <client xmlns="">
      <action xsi:nil="true">
      </action>
      <actionmode xsi:nil="true">
      </actionmode>
      <clientid>
       405965216
      </clientid>
      <firstname xsi:nil="true">
      </firstname>
      <id xsi:nil="true">
      </id>
      <lastname>
       Last Name
      </lastname>
      <role xsi:nil="true">
      </role>
      <state xsi:nil="true">
      </state>
     </client>
    </getservicebyidresponse>
   </soapenv:body>
  </soapenv:envelope>
 </body>
</html>

我会使用正则表达式并尝试获取我需要的行的值,但是有一个pythonic方式吗?有点像xml[0][1]等吗?

python xml python-2.6
1个回答
3
投票

正如@deceze已经指出的那样,你可以在这里使用xml.etree.ElementTree

import xml.etree.ElementTree as ET
tree = ET.parse("path_to_xml_file")
root = tree.getroot()

您可以迭代root的所有子节点:

for child in root.iter():
    if child.tag == 'clientid':
        print child.tag, child.text.strip()

子项是嵌套的,我们可以通过索引访问特定的子节点,因此root[0][1]应该可以工作(只要索引是正确的)。

© www.soinside.com 2019 - 2024. All rights reserved.