Python中的xml與dict的轉換方法詳解
接口文檔拿到的是XML,在線轉化為json格式(目的是拿到xml數(shù)據(jù)的模板),存放到json文件中,根據(jù)接口名去提取。
- xml 是指可擴展標記語言,一種標記語言類似html,作用是傳輸數(shù)據(jù),而且不是顯示數(shù)據(jù)??梢宰远x標簽。
- Python 中的xml和dict 互相轉化。使用的模塊是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 ,將字典轉成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 類型,轉成str。
print(type(ret_xml)) 利用循環(huá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轉化,如果需要轉化json,內(nèi)置的json模塊就可以完成,但是在自動化測試框架中這樣使用比較麻煩,而且復用性不好,封裝好如下
import xmltodict
"""
xml和dict轉換
"""
def dict_xml(dictdata):
"""
dict轉xml
dictstr: dict字符串
return: xml字符串
"""
xmlstr=xmltodict.unparse(dictdata, pretty=True)
return xmlstr
def xml_dict(xmldata,moudle):
"""
xml轉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到此這篇關于Python中的xml與dict的轉換方法詳解的文章就介紹到這了,更多相關Python中的xml與dict轉換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Scrapy-Redis之RedisSpider與RedisCrawlSpider詳解
這篇文章主要介紹了Scrapy-Redis之RedisSpider與RedisCrawlSpider詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-11-11
Python使用PySimpleGUI和Pygame編寫一個MP3播放器
這篇文章主要為大家詳細介紹了Python如何使用PySimpleGUI和Pygame編寫一個簡單的MP3播放器,文中的示例代碼講解詳細,感興趣的小伙伴可以學習一下2023-11-11
Python調(diào)用ChatGPT的API實現(xiàn)文章生成
最近ChatGPT大火,在3.5版本后開放了接口API,所以很多人開始進行實操,這里我就用python來為大家實現(xiàn)一下,如何調(diào)用API并提問返回文章的說明2023-03-03

