Python中读取XML

2024-10-04 07:26:28 发布

您现在位置:Python中文网/ 问答频道 /正文

<?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>

这个来自sopeapi的xml格式我想从这个表单读取xmlasessionid。请帮我用python做这个


Tags: orghttpversionwwwbodyxmlsoapencoding
1条回答
网友
1楼 · 发布于 2024-10-04 07:26:28

列表_测试.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

编辑:

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

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

相关问题 更多 >