我需要从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库。
使用标准W3 DOM,如stdlib的minidom或pxdom:
ElementTree 1.3(不幸的是不是Python中包含的1.2)supports XPath这样:
那你就可以了
lxml.etree
(它也提供ElementTree接口)也将以同样的方式工作。我不是Python的老手,但这里有一个使用libxml2的XPath解决方案。
结果。。。
相关问题 更多 >
编程相关推荐