这篇文章主要讲解了“python中的xmltodict怎么使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“python中的xmltodict怎么使用”吧!
python中xmltodict使用
xml转换成OrderedDict
代码 :
import xmltodict from pprint import pprint xml = (''' <mydocument has="an attribute"> <and> <many>elements</many> <many>more elements</many> </and> <plus a="complex" b="hello"> element as well </plus> </mydocument> ''') pprint(xmltodict.parse(xml)) print(type(xmltodict.parse(xml)))
运行结果:
可以看到,代码将xml中所有的标签写到了一个OrderedDict中,并且可以运用字典的操作方法去任意取值
dict转换成xml
代码:
# 代码 dict1 = {'Request': {'Body': {'Name': '孙悟空', 'Province': '北京', 'SettlementFlag': '0001', 'Head': {'ID': '00000000', 'Code': '9999', 'No': '15533'}}}} print(xmltodict.unparse(dict1))
运行结果:
xmltodict模块处理xml数据基本用法
xmltodict 是一个用来处理xml数据的很方便的模块。
包含两个常用方法parse和unparse
1. parse
xmltodict.parse()方法可以将xml数据转为python中的dict字典数据:
>>> import xmltodict >>> xml_str = """ ... <xml> ... <ToUserName><![CDATA[gh_866835093fea]]></ToUserName> ... <FromUserName><![CDATA[ogdotwSc_MmEEsJs9-ABZ1QL_4r4]]></FromUserName> ... <CreateTime>1478317060</CreateTime> ... <MsgType><![CDATA[text]]></MsgType> ... <Content><![CDATA[你好]]></Content> ... <MsgId>6349323426230210995</MsgId> ... </xml> ... """ >>> >>> xml_dict = xmltodict.parse(xml_str) >>> type(xml_dict) <class 'collections.OrderedDict'> # 类字典型,可以按照字典方法操作 >>> >>> xml_dict OrderedDict([(u'xml', OrderedDict([(u'ToUserName', u'gh_866835093fea'), (u'FromUserName', u'ogdotwSc_MmEEsJs9-ABZ1QL_4r4'), (u'CreateTime', u'1478317060'), (u'MsgType', u'text'), (u'Content', u'u4f60u597d'), (u'MsgId', u'6349323426230210995')]))]) >>> >>> xml_dict['xml'] OrderedDict([(u'ToUserName', u'gh_866835093fea'), (u'FromUserName', u'ogdotwSc_MmEEsJs9-ABZ1QL_4r4'), (u'CreateTime', u'1478317060'), (u'MsgType', u'text'), (u'Content', u'u4f60u597d'), (u'MsgId', u'6349323426230210995')]) >>> >>> for key, val in xml_dict['xml'].items(): ... print key, "=", val ... ToUserName = gh_866835093fea FromUserName = ogdotwSc_MmEEsJs9-ABZ1QL_4r4 CreateTime = 1478317060 MsgType = text Content = 你好 MsgId = 6349323426230210995 >>>
2. unparse
xmltodict.unparse()方法可以将字典转换为xml字符串:
xml_dict = { "xml": { "ToUserName" : "gh_866835093fea", "FromUserName" : "ogdotwSc_MmEEsJs9-ABZ1QL_4r4", "CreateTime" : "1478317060", "MsgType" : "text", "Content" : u"你好", "MsgId" : "6349323426230210995", } } >>> xml_str = xmltodict.unparse(xml_dict) >>> print xml_str <?xml version="1.0" encoding="utf-8"?> <xml><FromUserName>ogdotwSc_MmEEsJs9-ABZ1QL_4r4</FromUserName><MsgId>6349323426230210995</MsgId><ToUserName>gh_866835093fea</ToUserName><Content>你好</Content><MsgType>text</MsgType><CreateTime>1478317060</CreateTime></xml> >>> >>> xml_str = xmltodict.unparse(xml_dict, pretty=True) # pretty表示友好输出 >>> print xml_str <?xml version="1.0" encoding="utf-8"?> <xml> <FromUserName>ogdotwSc_MmEEsJs9-ABZ1QL_4r4</FromUserName> <MsgId>6349323426230210995</MsgId> <ToUserName>gh_866835093fea</ToUserName> <Content>你好</Content> <MsgType>text</MsgType> <CreateTime>1478317060</CreateTime> </xml> >>>