python解析xml存入字典_如何将xml字符串转换为字典?

这是网站上的代码,以防链接出错。from xml.etree 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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值