本文介绍了在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中做到这一点
This xml format coming form sope api i want to read xml aSessionID form this. Please help me to do this in python
推荐答案
list_test.xml:
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
编辑:
要从 string
而不是文件中读取 xml
,您可以使用:
To read the xml
from a string
rather than the file, you may use:
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
这篇关于在python中读取xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!