如何将xml字符串转换为Python中的字典? [英] How to convert an xml string to a dictionary in Python?
问题描述
simplejson
库中一样。 举个例子:
str =<?xml version =1.0 >< person>< name> john< / name>< age> 20< / age>< / person
dic_xml = convert_to_dic(str)
然后 dic_xml
将看起来像 {'person':{ 'name':'john','age':20}}
提前感谢,
Ze Maria
这是有人创建的一个很棒的模块。我用了好几次
http://code.activestate.com/recipes/410469- xml-as-dictionary /
这是来自网站的代码,以防链接变坏。
导入cElementTree作为ElementTree
类XmlListConfig(list):
def __init __(self ,aList):
for a element中的元素
如果元素:
#对待像dict
如果len(元素)== 1或元素[0] .tag!=元素[1] .tag:
self.append(XmlDictConfig(element))
#对待像
elif元素[0] .tag ==元素[1] .tag:
self.append(XmlListConfig(element))
elif element.text:
text = element.text.strip()
如果文本:
self.append(text)
class XmlDictConfig(dict):
'''
示例用法:
>>> tree = ElementTree.parse('your_file.xml')
>>> root = tree.getroot()
>>> xmldict = XmlDictConfig(root)
或者,如果要使用XML字符串:
>>> root = ElementTree.XML(xml_string)
>>> xmldict = XmlDictConfig(root)
然后使用xmldict是什么...一个dict。
'''
def __init __(self,parent_element):
如果parent_element.items():
self.update(dict(parent_element.items()))
for element in parent_element:
如果元素:
#对待像dict - 我们假设如果前两个标签
#在一系列中是不同的,那么它们都是不同的。
如果len(element)== 1或element [0] .tag!= element [1] .tag:
aDict = XmlDictConfig(element)
#对待像列表 - 我们假设如果一个系列中的前两个标签
#相同,则其余的都相同。
else:
#这里,我们把列表放在字典中;关键是
#标签名称列表元素全部共享,
#该值是列表本身
aDict = {element [0] .tag:XmlListConfig(element)}
#如果标签有属性,将这些添加到dict
如果element.items():
aDict.update(dict(element.items()))
self。 update({element.tag:aDict})
#这假设如果你在标签中有一个属性,
#你不会有任何文本。这可能是也可能不是一个
#的好主意 - 时间会告诉你。它的工作方式是我们
#当前正在做XML配置文件...
elif element.items():
self.update({element.tag:dict(element.items( )})
#finally,如果没有子标签,没有属性,提取
#文本
else:
self.update({element.tag:element。文本})
示例用法:
tree = ElementTree.parse('your_file.xml')
root = tree.getroot()
xmldict = XmlDictConfig(root)
//或者,如果要使用XML字符串:
root = ElementTree.XML(xml_string)
xmldict = XmlDictConfig(root)
I have a program that reads an xml document from a socket. I have the xml document stored in a string which I would like to convert directly to a Python dictionary, the same way it is done in Django's simplejson
library.
Take as an example:
str ="<?xml version="1.0" ?><person><name>john</name><age>20</age></person"
dic_xml = convert_to_dic(str)
Then dic_xml
would look like {'person' : { 'name' : 'john', 'age' : 20 } }
Thanks in advance,
Ze Maria
This is a great module that someone created. I've used it several times. http://code.activestate.com/recipes/410469-xml-as-dictionary/
Here is the code from the website just in case the link goes bad.
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})
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)
这篇关于如何将xml字符串转换为Python中的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!