xpath 到 dic python、lxml 和 xml

骑自行车的人

有没有一种快速的方法可以通过在 Python 中使用来自 lxml 的 xpath 将以下 xml 转换为字典?或者有什么其他有效的方法?

<rec item="1">
    <tag name="atr1">random text</tag>
    <tag name="atr2">random text</tag>
    ..................................        
</rec>
<rec item="2">
    <tag name="atr1">random text2</tag>
    <tag name="atr2">random text2</tag>
    ..................................        
</rec>
<rec item="3">
    <tag name="atr1">random text3</tag>
    <tag name="atr2">random text3</tag>
    ..................................        
</rec>

需要这样的字典,或其他类似的:

dic = [
    {    
        'attr1':'random text',
        'attr2':'random text'
    },
    {    
        'attr1':'random text2',
        'attr2':'random text2'
    },
    {    
        'attr1':'random text3',
        'attr2':'random text3'
    }
]
马丁·霍南

您可以将列表推导与字典推导一起使用:

[{ tag.xpath('string(@name)') : tag.xpath('string()') for tag in record.xpath('tag')} for record in records.xpath('//rec')]

这是一个完整的示例:

from lxml import etree as ET
xml = '''<records>
<rec item="1">
    <tag name="atr1">random text</tag>
    <tag name="atr2">random text</tag>
    ..................................        
</rec>
<rec item="2">
    <tag name="atr1">random text2</tag>
    <tag name="atr2">random text2</tag>
    ..................................        
</rec>
<rec item="3">
    <tag name="atr1">random text3</tag>
    <tag name="atr2">random text3</tag>
    ..................................        
</rec>
</records>'''
records = ET.fromstring(xml)
rec_list = [{ tag.xpath('string(@name)') : tag.xpath('string()') for tag in rec.xpath('tag') } for rec in records.xpath('rec')]
print(rec_list)

输出

[{'atr1': 'random text', 'atr2': 'random text'}, {'atr1': 'random text2', 'atr2': 'random text2'}, {'atr1': 'random text3', 'atr2': 'random text3'}]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章