获取Python中XML属性值的列表

2024-09-23 10:26:19 发布

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

我需要从Python中的子元素获取属性值列表。

用一个例子来解释是最容易的。

给定这样的XML:

<elements>
    <parent name="CategoryA">
        <child value="a1"/>
        <child value="a2"/>
        <child value="a3"/>
    </parent>
    <parent name="CategoryB">
        <child value="b1"/>
        <child value="b2"/>
        <child value="b3"/>
    </parent>
</elements>

我想做一些事情,比如:

>>> getValues("CategoryA")
['a1', 'a2', 'a3']
>>> getValues("CategoryB")
['b1', 'b2', 'b3']

这看起来像是XPath的一项工作,但我愿意接受所有的建议。我还想听听您最喜欢的Python XML库。


Tags: namechilda2valuea1xmlelementsb2
3条回答

使用标准W3 DOM,如stdlib的minidom或pxdom:

def getValues(category):
    for parent in document.getElementsByTagName('parent'):
        if parent.getAttribute('name')==category:
            return [
                el.getAttribute('value')
                for el in parent.getElementsByTagName('child')
            ]
    raise ValueError('parent not found')

ElementTree 1.3(不幸的是不是Python中包含的1.2)supports XPath这样:

import elementtree.ElementTree as xml

def getValues(tree, category):
    parent = tree.find(".//parent[@name='%s']" % category)
    return [child.get('value') for child in parent]

那你就可以了

>>> tree = xml.parse('data.xml')
>>> getValues(tree, 'CategoryA')
['a1', 'a2', 'a3']
>>> getValues(tree, 'CategoryB')
['b1', 'b2', 'b3']

lxml.etree(它也提供ElementTree接口)也将以同样的方式工作。

我不是Python的老手,但这里有一个使用libxml2的XPath解决方案。

import libxml2

DOC = """<elements>
    <parent name="CategoryA">
        <child value="a1"/>
        <child value="a2"/>
        <child value="a3"/>
    </parent>
    <parent name="CategoryB">
        <child value="b1"/>
        <child value="b2"/>
        <child value="b3"/>
    </parent>
</elements>"""

doc = libxml2.parseDoc(DOC)

def getValues(cat):
    return [attr.content for attr in doc.xpathEval("/elements/parent[@name='%s']/child/@value" % (cat))]

print getValues("CategoryA")

结果。。。

['a1', 'a2', 'a3']

相关问题 更多 >