Python中的xml與dict的轉(zhuǎn)換方法詳解
接口文檔拿到的是XML,在線轉(zhuǎn)化為json格式(目的是拿到xml數(shù)據(jù)的模板),存放到j(luò)son文件中,根據(jù)接口名去提取。
- xml 是指可擴展標記語言,一種標記語言類似html,作用是傳輸數(shù)據(jù),而且不是顯示數(shù)據(jù)??梢宰远x標簽。
- Python 中的xml和dict 互相轉(zhuǎn)化。使用的模塊是xmltodict。
import re
import xmltodict
xml="""<notes>
<to>demo</to>
<from>哈哈</from>
<header>呵呵</header>
<body>"尼古拉斯趙四"</body>
</notes>"""
dict = {"goods":{"fruits":{"name":"melon","coloer":"red","nut":"walnut"}}}
class XmlToDict(object):
def get_dict(self,xml):
"""xml to dict"""
return xmltodict.parse(xml_input=xml,encoding="utf-8")
def get_xml_content(self,orderdict):
for i in orderdict:
print(orderdict[str(i)])
def get_content(self,xml):
first_title = re.match(r"<.*>", xml).group()[1:-1]
orderdict = self.get_dict(xml)
orderdict=orderdict[first_title]
self.get_xml_content(orderdict)
def dicttoxml(self,dict):
"""dict to xml"""
return xmltodict.unparse(dict,encoding="utf-8")
if __name__ == '__main__':
XmlToDict().get_content(xml)
ret=XmlToDict().dicttoxml(dict)
print(ret)- python 中還有一個模塊dicttoxml ,將字典轉(zhuǎn)成xml
mport dicttoxml
dict= {"goods":{"fruits":{"name":"melon","coloer":"red","nut":"walnut"}}}
ret_xml = dicttoxml.dicttoxml(dict,custom_root="Request",root=True).decode("utf-8") # 默認是byte 類型,轉(zhuǎn)成str。
print(type(ret_xml)) 利用循環(huán)字典轉(zhuǎn)成xml
dict = {
"fruit": "apple",
"goods": "hamburger"
}
def dicttoxml(iKwargs):
xml = []
for k in sorted(iKwargs.keys()):
v =iKwargs.get(k)
xml.append("<{key}>{value}</{key}>".format(key=k,value=v))
return "<xml>{}</xml>".format("".join(xml))
ret=dicttoxml(dict)
print(ret)上面就是xml和dict轉(zhuǎn)化,如果需要轉(zhuǎn)化json,內(nèi)置的json模塊就可以完成,但是在自動化測試框架中這樣使用比較麻煩,而且復用性不好,封裝好如下
import xmltodict
"""
xml和dict轉(zhuǎn)換
"""
def dict_xml(dictdata):
"""
dict轉(zhuǎn)xml
dictstr: dict字符串
return: xml字符串
"""
xmlstr=xmltodict.unparse(dictdata, pretty=True)
return xmlstr
def xml_dict(xmldata,moudle):
"""
xml轉(zhuǎn)dict
xmlstr: xml字符串
moudle:根節(jié)點
return: dict字符串
"""
data=xmltodict.parse(xmldata,process_namespaces = True)
dictdata=dict(data)
_dictdata=dict(dictdata[moudle])
dictdata[moudle]=_dictdata
return dictdata到此這篇關(guān)于Python中的xml與dict的轉(zhuǎn)換方法詳解的文章就介紹到這了,更多相關(guān)Python中的xml與dict轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python基于Tkinter的HelloWorld入門實例
這篇文章主要介紹了Python基于Tkinter的HelloWorld入門實例,以一個簡單實例分析了Python中Tkinter模塊的使用技巧,需要的朋友可以參考下2015-06-06
Python使用ConfigParser解析INI配置文件的完全指南
配置文件提供了一種結(jié)構(gòu)化的方式來管理應用程序設(shè)置,比單獨使用環(huán)境變量更有組織性,INI文件采用簡單的基于部分的格式,既易于閱讀又易于解析,Python內(nèi)置的configparser模塊使處理這些文件變得簡單而強大,需要的朋友可以參考下2025-10-10

