从库的一个方法我得到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'
}
}
}
}
当我尝试使用此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})
答案 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