遍历 XML?

iterate through XML?

使用 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] 之类的东西?

正如@deceze 已经指出的,您可以在此处使用 xml.etree.ElementTree

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

您可以遍历根的所有 children 节点:

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

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