获取Python中XML属性值的列表 [英] Get list of XML attribute values in Python

查看:308
本文介绍了获取Python中XML属性值的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to get a list of attribute values from child elements in Python.

用示例最容易解释.

给出一些这样的XML:

Given some XML like this:

<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>

我希望能够做类似的事情:

I want to be able to do something like:

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

这似乎是XPath的工作,但我愿意接受所有建议.我也想听听您最喜欢的Python XML库.

It looks like a job for XPath but I'm open to all recommendations. I'd also like to hear about your favourite Python XML libraries.

推荐答案

我并不是使用Python的老手,但这是使用libxml2的XPath解决方案.

I'm not really an old hand at Python, but here's an XPath solution using libxml2.

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']

这篇关于获取Python中XML属性值的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆