[英]python lxml.etree._Element to JSON or dict
From one method of library I get lxml.etree._Element
, is there any library or function to convert an lxml.etree._Element
to JSON or a dictionary?从我得到的一种库方法
lxml.etree._Element
,是否有任何库或函数可以将lxml.etree._Element
转换为 JSON 或字典?
For example:例如:
<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>
Should be something like this:应该是这样的:
{
'detail': {
'Fault': {
'ResponseStatus': 'F'
'ResponseCode': '2013'
'ResponseData': {
'numParm': '1'
'text': 'The personal account was not found: 9134211141'
'category': '90006'
'number': '32200'
'parm1': '9134211141'
}
}
}
}
When I trying use this 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
And I get foo:我得到了 foo:
<class 'tuple'>: ('detail', {'ResponseCode': '2013', 'ResponseStatus': 'F', 'ResponseData': None})
The recursive_dict
method in the linked documentation doesn't include XML attribute in the result.链接文档中的
recursive_dict
方法在结果中不包含 XML 属性。 Assuming, for XML element that has attribute and doesn't have content (self-closing tag) you want to get the attributes as the dictionary value, the following modified version of recursive_dict
will do :假设,对于具有属性但不具有内容(自关闭标记)的 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.