python - 在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中做到这一点
解决方案
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
推荐阅读
- c# - 仅当使用 linq QueryableExpression 在 c# 中对数据库进行异步调用时才获取 ArgumentException
- sql - 加入具有日期范围的表
- python - 使用正则表达式匹配一列中的模式并根据列属性名称创建一个新列
- unity3d - 如何修复:“GameObject”类型的对象已被破坏,但您仍在尝试访问它?-统一
- f# - 如何使用 Elmish 调试器解决编码器问题?
- javascript - 具有不同 ID 的第二个模态以不同的效果打开 - 为什么?
- c - web_convert_param 用于 loadrunner 中的序数值
- python - 在 pandas udf pyspark 中使用 numpy
- flask - 用于生产的 K8s 上的普通 Flask 服务器与基于 UWSGI 的服务器?
- c++ - 获取/检查进程 win32 的内部 kernel32 状态(为了安全使用 TerminateThread )