Python 使用 SOAP 命名空间解析 XML

Python Parsing XML with SOAP Namespaces

如何使用 python XML 解析带命名空间的输出:

<?xml version="1.0" encoding="UTF-8"?><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>
    <ns1:searchResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://configuration.api.sitescope.mercury.com">
        <searchReturn href="#id0"/>
    </ns1:searchResponse>
    <multiRef id="id0" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns2:Map" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns2="http://xml.apache.org/xml-soap">
        <item>
            <key xsi:type="soapenc:string">test_sis_path_delimiter_www.google.com:443 on server www.google.com</key>
            <value xsi:type="soapenc:string">Group</value>
        </item>
    </multiRef>
</soapenv:Body>

我需要获取键和值。 谢谢!

要解析 XML,您可以使用 BeautifulSoup。此处示例:

data = """<?xml version="1.0" encoding="UTF-8"?><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>
    <ns1:searchResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://configuration.api.sitescope.mercury.com">
        <searchReturn href="#id0"/>
    </ns1:searchResponse>
    <multiRef id="id0" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns2:Map" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns2="http://xml.apache.org/xml-soap">
        <item>
            <key xsi:type="soapenc:string">test_sis_path_delimiter_www.google.com:443 on server www.google.com</key>
            <value xsi:type="soapenc:string">Group</value>
        </item>
    </multiRef>
</soapenv:Body>"""

from bs4 import BeautifulSoup

soup = BeautifulSoup(data, 'xml')

print(soup.key.text)
print(soup.value.text)

输出:

test_sis_path_delimiter_www.google.com:443 on server www.google.com
Group