python保存字典到xml文件_XML到/从Python字典

我最近编写了一些代码来将XML转换为python数据结构,尽管我确实需要处理属性。出于类似的原因,我使用了xml.dom.minidom,而不是ElementTree。我还没有在Python2.4.4上测试过它,但我认为它可以工作。我没有编写反向XML生成器,不过您可能可以使用我包含的“lispy_string”函数来执行此操作。

我还提供了一些特定于我正在编写的应用程序的快捷方式(在docstring中解释过),但是从它的声音中,您可能会发现这些快捷方式也很有用。从本质上讲,xml树从技术上转换为列表字典列表字典,等等。我省略了创建中间列表,除非它们是必需的,所以您可以通过dictname[element1][element2]而不是dictname[element1][0][element2][0]来引用元素。

属性处理有点笨拙,我强烈建议在使用属性之前先阅读代码。import sys

from xml.dom import minidom

def dappend(dictionary, key, item):

"""Append item to dictionary at key. Only create a list if there is more than one item for the given key.

dictionary[key]=item if key doesn't exist.

dictionary[key].append(item) if key exists."""

if key in dictionary.keys():

if not isinstance(dictionary[key], list):

lst=[]

lst.append(dictionary[key])

lst.append(item)

dictionary[key]=lst

else:

dictionary[key].append(item)

else:

dictionary.setdefault(key, item)

def node_attributes(node):

"""Return an attribute dictionary """

if node.hasAttributes():

return dict([(str(attr), str(node.attributes[attr].value)) for attr in node.attributes.keys()])

else:

return None

def attr_str(node):

return "%s-attrs" % str(node.nodeName)

def hasAttributes(node):

if node.nodeType == node.ELEMENT_NODE:

if node.hasAttributes():

return True

return False

def with_attributes(node, values):

if hasAttributes(node):

if isinstance(values, dict):

dappend(values, '#attributes', node_attributes(node))

return { str(node.nodeName): values }

elif isinstance(values, str):

return { str(node.nodeName): values,

attr_str(node): node_attributes(node)}

else:

return { str(node.nodeName): values }

def xmldom2dict(node):

"""Given an xml dom node tree,

return a python dictionary corresponding to the tree structure of the XML.

This parser does not make lists unless they are needed. For example:

'12' becomes:

{ 'list' : { 'item' : ['1', '2'] } }

BUT

'1' would be:

{ 'list' : { 'item' : '1' } }

This is a shortcut for a particular problem and probably not a good long-term design.

"""

if not node.hasChildNodes():

if node.nodeType == node.TEXT_NODE:

if node.data.strip() != '':

return str(node.data.strip())

else:

return None

else:

return with_attributes(node, None)

else:

#recursively create the list of child nodes

childlist=[xmldom2dict(child) for child in node.childNodes if (xmldom2dict(child) != None and child.nodeType != child.COMMENT_NODE)]

if len(childlist)==1:

return with_attributes(node, childlist[0])

else:

#if False not in [isinstance(child, dict) for child in childlist]:

new_dict={}

for child in childlist:

if isinstance(child, dict):

for k in child:

dappend(new_dict, k, child[k])

elif isinstance(child, str):

dappend(new_dict, '#text', child)

else:

print "ERROR"

return with_attributes(node, new_dict)

def load(fname):

return xmldom2dict(minidom.parse(fname))

def lispy_string(node, lst=None, level=0):

if lst==None:

lst=[]

if not isinstance(node, dict) and not isinstance(node, list):

lst.append(' "%s"' % node)

elif isinstance(node, dict):

for key in node.keys():

lst.append("\n%s(%s" % (spaces(level), key))

lispy_print(node[key], lst, level+2)

lst.append(")")

elif isinstance(node, list):

lst.append(" [")

for item in node:

lispy_print(item, lst, level)

lst.append("]")

return lst

if __name__=='__main__':

data = minidom.parse(sys.argv[1])

d=xmldom2dict(data)

print d

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值