python 从字符串中解析xml

本文主要解决,从字符串中解析xml的问题,很不完善,后续可能会补充

基本照抄这个网址的答案:https://zhidao.baidu.com/question/1430538621899888859.html

我的代码:

# 测试dom解析字符串xml
from xml.dom.minidom import parse
import xml.dom.minidom

#DOMtree = parseString("<Command>Ping</Command><Module><ModuleId>4</ModuleId></Module><ParameterList><Parameter><Type>xsd:string</Type><Name>AssemblyFileVersion</Name><Value>C:\test.dll - 1.0.13280.1</Value></Parameter><Parameter><Type>xsd:string</Type><Name>AssemblyFileVersion</Name><Value>C:\NetEx.dll - 1.0.14294.1</Value></Parameter><Parameter><Type>xsd:string</Type><Name>AssemblyFileVersion</Name><Value>C:\Nn.dll - 1.0.0.33112</Value></Parameter></ParameterList></root>")

#collection = DOMtree.document()

import xml.etree.ElementTree as Etree # 我可以称之它为最强吗?这个Etree真的爱了爱了,比起什么dom.minidom来,,,嘤嘤嘤,这个可以说一两句话就秒掉了所有问题,牛逼哦

# 参考的原答案
xml_str = """<root><ot><title>i am title</title></ot></root>"""
notify_data_tree = Etree.fromstring(xml_str)
str_value = notify_data_tree.find("ot/title").text
print(str_value )

# 仿写下
request_info = " <root><Command>Ping</Command><Module><ModuleId>"
"str(self.__module_id__)</ModuleId></Module><ParameterList>"
"<Parameter><Type>xsd:string</Type><Name>AssemblyFileVersion</Name>"
"<Value>str(assembly_file_version1)</Value></Parameter><Parameter><Type>xsd:string</Type><Name>AssemblyFileVersion</Name><Value>do</Value></Parameter><Parameter><Type>xsd:string</Type><Name>AssemblyFileVersion</Name><Value>str</Value></Parameter></ParameterList></root>"

tree_now = Etree.fromstring(request_info)
result = tree_now.find("Module/ModuleId").text # 这个是核心语句,真的很简明很友好,太好用了。直接就是向linux的那种文件格式出来的,太舒服了吧,特别的清晰
print(result)



原文地址:https://www.cnblogs.com/qihuanye-229110/p/13456635.html