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)




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM