roo*_*roo 13 python xml xpath parent-child xml-attribute
我需要从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>
Run Code Online (Sandbox Code Playgroud)
我希望能够做到这样的事情:
>>> getValues("CategoryA")
['a1', 'a2', 'a3']
>>> getValues("CategoryB")
['b1', 'b2', 'b3']
Run Code Online (Sandbox Code Playgroud)
它看起来像XPath的工作,但我对所有建议持开放态度.我也想听听你最喜欢的Python XML库.
我不是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")
Run Code Online (Sandbox Code Playgroud)
结果......
['a1', 'a2', 'a3']
Run Code Online (Sandbox Code Playgroud)
ElementTree 1.3(遗憾的是不是1.2包含在Python中的那个)支持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]
Run Code Online (Sandbox Code Playgroud)
那你可以做
>>> tree = xml.parse('data.xml')
>>> getValues(tree, 'CategoryA')
['a1', 'a2', 'a3']
>>> getValues(tree, 'CategoryB')
['b1', 'b2', 'b3']
Run Code Online (Sandbox Code Playgroud)
lxml.etree (也提供ElementTree接口)也将以相同的方式工作.