pythonlxml.etree.u元素转换为JSON或di

2024-10-02 18:18:47 发布

您现在位置:Python中文网/ 问答频道 /正文

从库的一个方法得到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>

应该是这样的:

^{pr2}$

更新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})

Tags: textselffooelementlxmldictetreerecursive
1条回答
网友
1楼 · 发布于 2024-10-02 18:18:47

链接文档中的recursive_dict方法没有在结果中包含XML属性。假设对于具有attribute且没有内容的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

相关问题 更多 >