我有一个XML SOAP响应:

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Header/>
  <soapenv:Body>
    <trk:TrackResponse xmlns:trk="http://www.web.com/XMLSchema/Track/v2.0">
      <trk:Package>
        <trk:Activity>
          <trk:ActivityLocation>
            <trk:Address>
              <trk:City>RUEMLANG</trk:City>
              <trk:CountryCode>CH</trk:CountryCode>
            </trk:Address>
          </trk:ActivityLocation>
        </trk:Activity>
        <trk:Activity>
          <trk:ActivityLocation>
            <trk:Address>
              <trk:City>BERLIN</trk:City>
              <trk:CountryCode>DE</trk:CountryCode>
            </trk:Address>
          </trk:ActivityLocation>
        </trk:Activity>
      </trk:Package>
    </trk:TrackResponse>
  </soapenv:Body>
</soapenv:Envelope>


我正在尝试在<trk:City>之间找到城市,但无法弄清楚。
我尝试了以下但没有任何结果

import xml.etree.ElementTree
e = xml.etree.ElementTree.parse('test.xml').getroot()
for element in e.findall('.//trk:City'):
    print (element.text)

最佳答案

您需要为名称空间使用前缀。

import xml.etree.ElementTree
e = xml.etree.ElementTree.parse('test.xml').getroot()
ns = {'trk':'http://www.web.com/XMLSchema/Track/v2.0'}

for element in e.findall('.//trk:City', ns):
    print (element.text)


版画

RUEMLANG
BERLIN

关于python - 从SOAP响应中解析多个值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48141064/

10-12 18:21