博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何将xml转为python中的字典
阅读量:6935 次
发布时间:2019-06-27

本文共 2860 字,大约阅读时间需要 9 分钟。

如何将xml转为python中的字典

import cElementTree as ElementTreeclass XmlListConfig(list):    def __init__(self, aList):        for element in aList:            if element:                # treat like dict                if len(element) == 1 or element[0].tag != element[1].tag:                    self.append(XmlDictConfig(element))                # treat like list                elif element[0].tag == element[1].tag:                    self.append(XmlListConfig(element))            elif element.text:                text = element.text.strip()                if text:                    self.append(text)class XmlDictConfig(dict):    '''    Example usage:    >>> tree = ElementTree.parse('your_file.xml')    >>> root = tree.getroot()    >>> xmldict = XmlDictConfig(root)    Or, if you want to use an XML string:    >>> root = ElementTree.XML(xml_string)    >>> xmldict = XmlDictConfig(root)    And then use xmldict for what it is... a dict.    '''    def __init__(self, parent_element):        if parent_element.items():            self.update(dict(parent_element.items()))        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 different.                if 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 same.                else:                    # 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 itself                     aDict = {element[0].tag: XmlListConfig(element)}                # if the tag has attributes, add those to the dict                if element.items():                    aDict.update(dict(element.items()))                self.update({element.tag: 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            # currently doing XML configuration files...            elif element.items():                self.update({element.tag: dict(element.items())})            # finally, if there are no child tags and no attributes, extract            # the text            else:                self.update({element.tag: element.text})

用法示例:

tree = ElementTree.parse('your_file.xml') root = tree.getroot() xmldict = XmlDictConfig(root)

//或者,如果你想使用一个XML字符串:

root = ElementTree.XML(xml_string) xmldict = XmlDictConfig(root) 学习了 https://cloud.tencent.com/developer/ask/51220 http://code.activestate.com/recipes/410469-xml-as-dictionary/

转载地址:http://swmjl.baihongyu.com/

你可能感兴趣的文章
表变量在存储过程或sql server中的运用
查看>>
【object-c基础】Object-c基础之一:#import,NSLog(),数据类型
查看>>
tablediff同步
查看>>
C#定义属性-只读属性
查看>>
小小聊天室
查看>>
几个不错的网站
查看>>
postmaster.c 中的 ListenAddresses
查看>>
.NET_.NET 发布(publish)网站_01-2
查看>>
文件处理
查看>>
c# 读写 xml
查看>>
使用<frameset><frame/><frame/></frameset> 布局页面 (div+css布局 和frameset布局,两种并列策略)...
查看>>
RDLC子报表
查看>>
2012-09-03 → 2012-09-09 周总结
查看>>
通过设置nginx的client_max_body_size解决nginx+php上传大文件的问题
查看>>
.net调试插件sosex的mk命令显示调用堆栈
查看>>
.NET开发者可以在Windows 8中使用ARM
查看>>
模板和标准模板库
查看>>
(原創) Function Pointer、Delegate和Function Object (C/C++) (template) (.NET) (C#)
查看>>
【C#】隐式类型var
查看>>
关于Jquery中ajax方法data参数用法的总结
查看>>