admin 管理员组文章数量: 887021
2024年1月24日发(作者:三角函数诱导公式大全图片)
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字符串转换为字典? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/free/1706032018h498928.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论