如何将xml转为python中的字典

import cElementTree as ElementTree

class 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/

如何将xml转为python中的字典的更多相关文章

  1. Python中的字典与集合

    今天我们来讲一讲python中的字典与集合 Dictionary:字典 Set:集合 字典的语法: Dictionary字典(键值对) 语法: dictionary = {key:value,key: ...

  2. python中 字符 字典 列表之间的转换

    1 字典 转 字符 定义一个字典:dict = {'name': 'python', 'age': 7}字典转字符 可以使用str强制转换 如: str(dict) 此时dict的类型就是字符型了 2 ...

  3. 13.python中的字典

    字典其实和之前的元祖和列表功能相似,都是用来储存一系列对象的.也就是一种可变容器,或者是我所比喻的革新派的菜单. 但也不是完全相同,我在之前曾经将字典称为特殊的'序列',是字典拥有序列的部分特性,但是 ...

  4. python中的字典(dict),列表(list),元组(tuple)

    一,List:列表 python内置的一种数据类型是列表:list.list是一种有序的数据集合,可以随意的添加和删除其中的数据.比如列出班里所有的同学的名字,列出所有工厂员工的工号等都是可以用到列表 ...

  5. Python中字符串/字典/json之间的转换

    import json #定义一个字典d1,字典是无序的 d1 = { "a": None, "b": False, "c": True, ...

  6. python中的字典 和 集合

    python中字典是一种key-value的数据类型 字典的特性: 1.无序的 2.key必须的唯一的,so,字典天生去重 语法: 增加 修改 删除 查找 多级字典嵌套及操作 字典的其他用法 #set ...

  7. python中的字典内置方法小结

    #!/usr/local/bin/python3 # -*- coding:utf-8 -*- #key-value #dict 无序,无下标,不需要下标,因为有key stu={ 'stu001': ...

  8. python学习之【第六篇】:Python中的字典及其所具有的方法

    1.前言 字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据.python对key进行哈希函数运算,根据计算的结果决定value的存储地址,因此,字典的key必须是可哈 ...

  9. Python中的字典和集合

    一.字典(dict)      1. 概述          字典是Python唯一的映射类型. 只能使用不可变的对象(比如字符串)来作为字典的键,但是可以把不可变或可变的对象作为字典的值. 键值对在 ...

随机推荐

  1. django设置数据库事务,通过异常处理回滚事务

    1.setting.py配置文件,开启事务ATOMIC_REQUESTS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql' ...

  2. 【枚举】【贪心】Codeforces Round #482 (Div. 2) B. Treasure Hunt

    题意:给你3个字符串,3个人各对自己的字符串执行n轮操作,每一次选择一个字符变为任意一个和原来不同的字符.最后问你谁能使自己的串中的任意重复子串出现的次数最大化. 显然只需关注字符而非子串. 枚举每个 ...

  3. Codeforces Round #298 (Div. 2) B. Covered Path 物理题/暴力枚举

    B. Covered Path Time Limit: 1 Sec  Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/534/probl ...

  4. Codeforces Round #295 (Div. 2)B - Two Buttons BFS

    B. Two Buttons time limit per test 2 seconds memory limit per test 256 megabytes input standard inpu ...

  5. gridview DataFormatString 属性设置须知

    设置 DataFormatString 进行格式化数据时默认情况下是不会起作用的还有设置HtmlEncode = "false" 具体为什么?以下几点1. 在GridView中的a ...

  6. Python的静态方法和类成员方法

    http://www.cnblogs.com/2gua/archive/2012/09/03/2668125.html Python的静态方法和类成员方法都可以被类或实例访问,两者概念不容易理清,但还 ...

  7. TASKER 手机在有同一个号码的三个未接电话时自动回复短信

    http://tieba.baidu.com/p/3695018030 感谢默默为Tasker吧奉献的人! 配置为>未接来电 任务为>代码>javascriptlet 代码为: va ...

  8. Inside Portable Class Libraries

    Portable Class Libraries were introduced with Visual Studio 2010 SP1 to aid writing libraries that c ...

  9. MVC使用AdditionalMetadata为Model属性添加额外信息

    当需要为Model的属性添加一些额外信息的时候,使用[AdditionalMetadata("somekey", "some content")]是不错的选择, ...

  10. andriod 获得MP4时长

    //获得MP4时长 private int getTimeLong(String videoPath) { MediaMetadataRetriever retr = new MediaMetadat ...