如何在python中的XML中获取给定特定属性的父母和祖父母标签?



我有一个结构如下的xml:

<cat>
<foo>
<fooID>1</fooID>
<fooName>One</fooName>
<bar>
<barID>a</barID>
<barName>small_a</barName>
<barClass>
<baz>
<qux>
<corge>
<corgeName>...</corgeName>
<corgeType>
<corgeReport>
<corgeReportRes Reference="x" Channel="High">
<Pos>1</Pos>
</corgeReportRes>
</corgeReport>
</corgeType>
</corge>
</qux>
</baz>
</barClass>
</bar>
<bar>
<barID>b</barID>
<barName>small_b</barName>
<barClass>
<baz>
<qux>
<corge>
<corgeName>...</corgeName>
<corgeType>
<corgeReport>
<corgeReportRes Reference="y" Channel="High">
<Pos>1</Pos>
</corgeReportRes>
</corgeReport>
</corgeType>
</corge>
</qux>
</baz>
</barClass>
</bar>
</foo>
<foo>
<fooID>2</fooID>
<fooName>Two</fooName>
<bar>
<barID>c</barID>
<barName>small_c</barName>
<barClass>
<baz>
<qux>
<corge>
<corgeName>...</corgeName>
<corgeType>
<corgeReport>
<corgeReportRes Reference="z" Channel="High">
<Pos>1</Pos>
</corgeReportRes>
</corgeReport>
</corgeType>
</corge>
</qux>
</baz>
</barClass>
</bar>
</foo>
</cat>

而且,我想获取具有属性Channel="High"的节点的特定父/祖父/祖父标签的值。我只想获取 fooID 值、fooName 值、barID 值、barName 值。

我在 Python 3 中有以下代码:

import xml.etree.ElementTree as xmlET
root = xmlET.parse('file.xml').getroot()
test = root.findall(".//*[@Channel='High']")

这实际上给了我一个匹配的元素列表,但是,我仍然需要特定父母/祖父母/祖父母的信息。

我该怎么做?

fooID | fooName | barID | barName
- - - - - - - - - - - - - - - - -
1     |     One |     a | small_a  <-- This is the information I'm interested
1     |     One |     b | small_b  <-- Also this
2     |     Two |     c | small_c  <-- And this

编辑:fooID节点和fooName节点是外祖父bar的兄弟姐妹,包含Channel="High"的节点。barIDbarName的情况几乎相同,他们是包含Channel="High"的祖父母barClass的兄弟姐妹。另外,我想获得的是值1Oneasmall_a,而不是通过它过滤,因为会有多个 foo 块。

如果我理解正确,您可能正在寻找这样的东西(使用 python(:

from lxml import etree
foos = """[your xml above]"""
items = []
for entry in doc.xpath('//foo[.//corgeReportRes[@Channel="High"]]'):
items.append(entry.xpath('./fooID/text()')[0])
items.append(entry.xpath('./fooName/text()')[0])
items.append(entry.xpath('./bar/barID/text()')[0])
items.append(entry.xpath('./bar/barName/text()')[0])
print('fooID | fooName | barID | barName')
print('  |  '.join(items))

输出:

fooID | fooName | barID | barName
1  |  One  |  a  |  small_a

最新更新