python解析xml⽂件成字典_如何将xml字符串转换为字典?如何将xml字符串转换为字典?
我有⼀个程序从套接字读取xml⽂档。 我将xml⽂档存储在⼀个字符串中,我希望将其直接转换为Python字典,就像在Django的dic_xml 库中⼀样。
举个例⼦:
str ="<?xml version="1.0" ?>john20
dic_xml = convert_to_dic(str)
那么dic_xml看起来像{'person' : { 'name' : 'john', 'age' : 20 } }
15个解决⽅案
226 votes
xmltodict(完全披露:我写的)完全是这样的:
xmltodict.parse("""
john
20
""")
# {u'person': {u'age': u'20', u'name': u'john'}}
Martin Blech answered 2019-08-20T09:17:55Z
42 votes
这是⽹站上的代码,以防链接变坏。
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))
:
text = strip()
if text:
self.append(text)
class XmlDictConfig(dict):
'''
Example usage:
>>> tree = ElementTree.parse('l')
>>> root = t()
>>> 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 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
python解析json文件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
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: })
⽤法⽰例:
tree = ElementTree.parse('l')
root = t()
xmldict = XmlDictConfig(root)
//或者,如果要使⽤XML字符串:
root = ElementTree.XML(xml_string)
xmldict = XmlDictConfig(root)
James answered 2019-08-20T09:17:29Z
36 votes
以下XML-to-Python-dict⽚段解析实体以及遵循此XML-to-JSON&#34;规范&#34;的属性。 它是处理所有XML案例的最通⽤的解决⽅案。
from collections import defaultdict
def etree_to_dict(t):
d = {t.tag: {} if t.attrib els
e None}
children = list(t)
if children:
dd = defaultdict(list)
for dc in map(etree_to_dict, children):
for k, v in dc.items():
dd[k].append(v)
d = {t.tag: {k:v[0] if len(v) == 1 els
e v for k, v in dd.items()}}
if t.attrib:
d[t.tag].update(('@' + k, v) for k, v in t.attrib.items())
:
text = t.text.strip()
if children or t.attrib:
if text:
d[t.tag]['#text'] = text
else:
d[t.tag] = text
return d
它⽤于:
import cElementTree as ET
e = ET.XML('''
text
text
text text
text
text text
text text
''')
from pprint import pprint
pprint(etree_to_dict(e))
switchport access是什么意思
此⽰例的输出(按照上⾯链接的&#34;规范&#34;)应该是:
系统 开发{'root': {'e': [None,
'text',
{'@name': 'value'},
{'#text': 'text', '@name': 'value'},
{'a': 'text', 'b': 'text'},
{'a': ['text', 'text']},
{'#text': 'text', 'a': 'text'}]}}
不⼀定很漂亮,但它是明确的,更简单的XML输⼊导致更简单的JSON。:)更新
如果你想反过来,从JSON / dict发出⼀个XML字符串,你可以使⽤:try:
basestring
except NameError: # python3
basestring = str
def dict_to_etree(d):
def _to_etree(d, root):
if not d:
pass
elif isinstance(d, basestring):
< = d
elif isinstance(d, dict):
for k,v in d.items():
assert isinstance(k, basestring)
if k.startswith('#'):
assert k == '#text' and isinstance(v, basestring)
< = v
elif k.startswith('@'):
assert isinstance(v, basestring)
root.set(k[1:], v)
elif isinstance(v, list):
for e in v:
_to_etree(e, ET.SubElement(root, k))
else:
_to_etree(v, ET.SubElement(root, k))
else:
raise TypeError('invalid type: ' + str(type(d)))
边框简笔画可爱花纹assert isinstance(d, dict) and len(d) == 1
tag, body = next(iter(d.items()))
node = ET.Element(tag)
_to_etree(body, node)
string(node)
pprint(dict_to_etree(d))
K3---rnc answered 2019-08-20T09:18:53Z
22 votes
这个轻量级版本虽然不可配置,但很容易根据需要进⾏定制,并且适⽤于旧的蟒蛇。 它也很严格 - 意味着⽆论属性是否存在,结果都是相同的。
ElementTree as ET
from copy import copy
def dictify(r,root=True):
if root:
return {r.tag : dictify(r, False)}
d=copy(r.attrib)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。