python解析xml文件成字典_如何将xml字符串转换为字典?

阅读: 评论:0

2024年1月30日发(作者:)

python解析xml文件成字典_如何将xml字符串转换为字典?

class XmlDictConfig(dict):'''Example usage:>>> tree = ('your_')>>> root = t()>>> xmldict = XmlDictConfig(root)Or, if you want to use an XML string:>>> root = (xml_string)>>> xmldict = XmlDictConfig(root)And then use xmldict for what a dict.'''def __init__(self, parent_element):if parent_():(dict(parent_()))for element in parent_element:if element:# treat like dict - we assume that if the first two tags# in a series are different, then they are all len(element) == 1 or element[0].tag != element[1].tag:aDict = XmlDictConfig(element)# treat like list - we assume that if the first two tags# in a series are the same, then the rest are the :# here, we put the list in dictionary; the key is the# tag name the list elements all share in common, and# the value is the list itselfaDict = {element[0].tag: XmlListConfig(element)}# if the tag has attributes, add those to the dictif ():(dict(()))({: aDict})# this assumes that if you've got an attribute in a tag,# you won't be having any text. This may or may not be a# good idea -- time will tell. It works for the way we are

from m import parseclass NotTextNodeError:passdef getTextFromNode(node):"""scans through all children of node and gathers thetext. if node has non-text child-nodes, thenNotTextNodeError is raised."""t = ""for n in odes:if pe == _NODE:t += lueelse:raise NotTextNodeErrorreturn tdef nodeToDic(node):"""nodeToDic() scans through the children of node and makes adictionary from the cases are differentiated:- if the node contains no other nodes, it is a text-nodeand {nodeName:text} is merged into the dictionary.- if the node has the attribute "method" set to "true",then it's children will be appended to a list and thislist is merged to the dictionary in the form: {nodeName:list}.- else, nodeToDic() will call itself recursively onthe nodes children (merging {nodeName:nodeToDic()} tothe dictionary)."""dic = {}for n in odes:if pe != T_NODE:continue

if ribute("multiple") == "true":# node with multiple children:# put them in a listl = []for c in odes:if pe != T_NODE:(nodeToDic(c))({me:l})continuetry:text = getTextFromNode(n)except NotTextNodeError:# 'normal' ({me:nodeToDic(n)})continue# text ({me:text})continuereturn dicdef readConfig(filename):dom = parse(filename)return nodeToDic(dom)def test():dic = readConfig("")print dic["Config"]["Name"]printfor item in dic["Config"]["Items"]:print "Item's Name:", item["Name"]print "Item's Value:", item["Value"]test()==================================================:==================================================

return resultreturn {: xmltodict_handler(element)}def dicttoxml(element):if not isinstance(element, dict):raise ValueError("must pass dict type")if len(element) != 1:raise ValueError("dict must have exactly one root key")def dicttoxml_handler(result, key, value):if isinstance(value, list):for e in value:dicttoxml_handler(result, key, e)elif isinstance(value, basestring):elem = t(key) = (elem)elif isinstance(value, int) or isinstance(value, float):elem = t(key) = str(value)(elem)elif value is None:(t(key))else:res = t(key)for k, v in ():dicttoxml_handler(res, k, v)(res)result = t(()[0])for key, value in element[()[0]].items():dicttoxml_handler(result, key, value)return resultdef xmlfiletodict(filename):return xmltodict((filename).getroot())def dicttoxmlfile(element, filename):tTree(dicttoxml(element)).write(filename)

python解析xml文件成字典_如何将xml字符串转换为字典?

本文发布于:2024-01-30 05:05:23,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170656232319428.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:字典   解析   转换   文件   字符串
留言与评论(共有 0 条评论)
   
验证码:
排行榜

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23