python lxml.etree._Element到JSON或dict

时间:2017-03-21 10:55:48

标签: python json lxml

从库的一个方法我得到lxml.etree._Element,是否有任何库或函数可以将lxml.etree._Element转换为JSON或字典?

例如:

<detail>
    <ouaf:Fault xmlns:ouaf="urn:oracle:ouaf">
        <ResponseStatus>F</ResponseStatus>
        <ResponseCode>2013</ResponseCode>
        <ResponseData numParm="1"  text="The personal account was not found: 9134211141"  category="90006"  number="32200"  parm1="9134211141"  />
    </ouaf:Fault>
</detail>

应该是这样的:

{
    'detail': {
        'Fault': {
            'ResponseStatus': 'F'
            'ResponseCode': '2013'
            'ResponseData': {
                'numParm': '1'
                'text': 'The personal account was not found: 9134211141'
                'category': '90006'
                'number': '32200'
                'parm1': '9134211141'
            }           
        }
    }
}

更新1:

当我尝试使用此function

def conver_element(self, element):
        foo = self.recursive_dict(element)
        return foo

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

我得到了foo:

<class 'tuple'>: ('detail', {'ResponseCode': '2013', 'ResponseStatus': 'F', 'ResponseData': None})

1 个答案:

答案 0 :(得分:2)

链接文档中的recursive_dict方法在结果中不包含XML属性。假设,对于具有属性且没有内容的XML元素(自闭标签),您希望将属性作为字典值,以下recursive_dict的修改版本将执行:

def recursive_dict(element):
    if element.text == None and len(element.attrib):
        return element.tag, element.attrib
    return element.tag, \
            dict(map(recursive_dict, element)) or element.text