使用lxml将XML转换为Python中的字典

时间:2014-10-31 01:49:09

标签: python xml dictionary

StackOverflow上似乎有很多解决方案用于将XML转换为Python字典,但它们都没有生成我正在寻找的输出。我有以下XML:

<?xml version="1.0" encoding="UTF-8"?>
<status xmlns:mystatus="http://localhost/mystatus">
<section1
    mystatus:field1="data1"
    mystatus:field2="data2" />
<section2
    mystatus:lineA="outputA"
    mystatus:lineB="outputB" />
</status>

lxml has an elegantly simple solution用于将XML转换为字典:

def recursive_dict(element):
 return element.tag, dict(map(recursive_dict, element)) or element.text

不幸的是,我得到了:

('status', {'section2': None, 'section1': None})

而不是:

('status', {'section2': 
                       {'field1':'data1','field2':'data2'}, 
            'section1': 
                       {'lineA':'outputA','lineB':'outputB'}
            })

我无法弄清楚如何获得我想要的输出而不会使recursive_dict()函数复杂化。

我与lxml没有关联,而且我对字典的不同组织也很好,只要它能给我xml中的所有信息。谢谢!

2 个答案:

答案 0 :(得分:10)

我个人喜欢来自herexmltodict。使用pip,您可以像pip install xmltodict一样安装它。

请注意,这实际上会创建OrderedDict个对象。用法示例:

import xmltodict as xd

with open('test.xml','r') as f:
    d = xd.parse(f)

答案 1 :(得分:1)

我在这个要点中找到了一个解决方案:https://gist.github.com/jacobian/795571

def elem2dict(node):
    """
    Convert an lxml.etree node tree into a dict.
    """
    result = {}

    for element in node.iterchildren():
        # Remove namespace prefix
        key = element.tag.split('}')[1] if '}' in element.tag else element.tag

        # Process element as tree element if the inner XML contains non-whitespace content
        if element.text and element.text.strip():
            value = element.text
        else:
            value = elem2dict(element)
        if key in result:

            
            if type(result[key]) is list:
                result[key].append(value)
            else:
                tempvalue = result[key].copy()
                result[key] = [tempvalue, value]
        else:
            result[key] = value
    return result