python-3.x - python - 如何在python中获取给定特定属性的父母和祖父母标签?
问题描述
我有一个结构像这样的 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"
. barID
和的情况几乎相同barName
,它们是祖父母的兄弟姐妹,祖父母barClass
包含Channel="High"
. 此外,我想要获得的是值1
、和One
,而不是通过它过滤,因为会有多个 foo 块。a
small_a
解决方案
如果我理解正确,您可能正在寻找这样的东西(使用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
推荐阅读
- php - 如何在不呈现 httpException 页面的情况下使用 symfony 捕获异常
- python - 在 Geopandas 中进行交叉时出现 TopologyException 问题?
- delphi - 将带有证书处理的 2007 C++Builder SOAP 代码移至 Delphi2018-Indy10
- php - 带有 PayPal REST API 的信用卡
- sas - Proc Report - 两个表的行
- python - 芹菜任务未在部署在 Heroku 上的 Django 应用程序中执行
- reactjs - 在创建反应应用程序中使用两种不同类型的 React 导致反应错误(在未安装的组件上调用了 findDOMNode。)
- java - 商米V1s设备-打印机打印完成后Java回调不起作用
- tensorflow - Keras如何保存指定的变量?
- javascript - 我想让 Javascript 对象动态化