首页 > 解决方案 > 在python中读取xml

问题描述

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <LoginResponse xmlns="http://tempuri.org/">
            <LoginResult>true</LoginResult>
            <aSessionID>AF-6A-51-FD-E6-8D-C8-12-AB-7E-C1-BD-50-7A-43-D0-AA-27-15-CA</aSessionID>
        </LoginResponse>
    </soap:Body>
</soap:Envelope>

这个 xml 格式来自 sope api 我想从这个中读取 xml aSessionID。请帮我在python中做到这一点

标签: pythonxml

解决方案


list_test.xml:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <LoginResponse xmlns="http://tempuri.org/">
            <LoginResult>true</LoginResult>
            <aSessionID>AF-6A-51-FD-E6-8D-C8-12-AB-7E-C1-BD-50-7A-43-D0-AA-27-15-CA</aSessionID>
            <aSessionID>54F-6A-51-FD-E6-8D-C8-45-AB-7E-C1-BD-50-7A-43-D0-AA-27-15-65</aSessionID>
        </LoginResponse>
    </soap:Body>
</soap:Envelope>

接着:

from xml.dom import minidom

doc = minidom.parse("list_test.xml")
sessionList = doc.getElementsByTagName('aSessionID')

for sess in sessionList:
    print(sess.firstChild.nodeValue)

输出

AF-6A-51-FD-E6-8D-C8-12-AB-7E-C1-BD-50-7A-43-D0-AA-27-15-CA
54F-6A-51-FD-E6-8D-C8-45-AB-7E-C1-BD-50-7A-43-D0-AA-27-15-65

编辑

xml要从astring而不是文件中读取,您可以使用:

minidom.parseString(xml_str)

因此:

from xml.dom import minidom

xml_str = '''<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <LoginResponse xmlns="http://tempuri.org/">
            <LoginResult>true</LoginResult>
            <aSessionID>AF-6A-51-FD-E6-8D-C8-12-AB-7E-C1-BD-50-7A-43-D0-AA-27-15-CA</aSessionID>
            <aSessionID>54F-6A-51-FD-E6-8D-C8-45-AB-7E-C1-BD-50-7A-43-D0-AA-27-15-65</aSessionID>
        </LoginResponse>
    </soap:Body>
</soap:Envelope>'''
doc = minidom.parseString(xml_str)
sessionList = doc.getElementsByTagName('aSessionID')

for sess in sessionList:
    print(sess.firstChild.nodeValue)

输出

AF-6A-51-FD-E6-8D-C8-12-AB-7E-C1-BD-50-7A-43-D0-AA-27-15-CA
54F-6A-51-FD-E6-8D-C8-45-AB-7E-C1-BD-50-7A-43-D0-AA-27-15-65

推荐阅读