LXML,如何获取多组属性到列表

时间:2011-12-30 10:05:31

标签: python xml lxml

我有类似的问题:

  

How do I select multiple sets of attributes within an XML document using XPath?

我的XML数据如下所示:

<?xml version="1.0" encoding="utf-8"?>
<Basic>
    <Segment>
        <Sample value="12" data2="25" data3="23"/>
        <Sample value="13" data2="0" data3="323"/>
        <Sample value="14" data2="2" data3="3"/>
    </Segment>
</Basic>

datax值列入列表的最简单的python方法是什么。

例如:data2 = ['25','0','2']

3 个答案:

答案 0 :(得分:5)

使用xpath:

from lxml import etree
from collections import defaultdict
from pprint import pprint

doc="""<?xml version="1.0" encoding="utf-8"?>
<Basic>
    <Segment>
        <Sample value="12" data2="25" data3="23"/>
        <Sample value="13" data2="0" data3="323"/>
        <Sample value="14" data2="2" data3="3"/>
    </Segment>
</Basic>
"""
el = etree.fromstring(doc)
data2 = el.xpath('//@data2')
dataX = el.xpath('//@*[starts-with(name(), "data")]')
print data2
print dataX

# With iteration over Sample elements, like in J.F. Sebastian answer, but with XPath
d = defaultdict(list)
for sample in el.xpath('//Sample'):
    for attr_name, attr_value in sample.items():
        d[attr_name].append(attr_value)

pprint(dict(d))

输出:

['25', '0', '2']
['25', '23', '0', '323', '2', '3']
{'data2': ['25', '0', '2'],
 'data3': ['23', '323', '3'],
 'value': ['12', '13', '14']}

答案 1 :(得分:1)

获取属性值的最简单方法是使用etree.Element.get('attr_name'):

scan

答案 2 :(得分:0)

使用stdlib中的cElementTree

import sys
from collections import defaultdict
from xml.etree import cElementTree as etree

d = defaultdict(list)
for ev, el in etree.iterparse(sys.stdin):
    if el.tag == 'Sample':
       for name in "value data2 data3".split():
           d[name].append(el.get(name))
print(d)

Output

{'data2': ['25', '0', '2'],
 'data3': ['23', '323', '3'],
 'value': ['12', '13', '14']}

如果您使用lxml.etree,则可以:etree.iterparse(file, tag='Sample')选择Sample中的iterparse()元素,即在这种情况下您可以删除if el.tag == 'Sample'条件。< / p>