XML.Etree Get get Tag,其具有特定属性的孩子

发布于 2025-02-08 10:15:07 字数 607 浏览 2 评论 0原文

我有以下XML文件:

<node id="1416646243" />
<node id="1416646244">
    <tag k="crossing" v="unregulated" />
</node>
<node id="1416646245">
    <tag k="crossing" v="traffic_signals" />
</node>

我想选择&lt; node&gt;标签,其中包含a &lt; tag&gt;带有atteribute v =“ copery_signals” < /code>。
但是,如果我使用以下代码,则在返回中获得&lt; tag&gt;标签。

root.find('.// node/tag [@v =“ crigings_signals”]')

,据我所知,xml.etree不提供一个获得父母的方法。

我如何真正获得节点标签?

I have the following xml file:

<node id="1416646243" />
<node id="1416646244">
    <tag k="crossing" v="unregulated" />
</node>
<node id="1416646245">
    <tag k="crossing" v="traffic_signals" />
</node>

I want to select the <node> tag which contains a <tag> tag with attribute v="traffic_signals".
However if I use the following code, I get the <tag> tag in return.

root.find('.//node/tag[@v="traffic_signals"]')

And as far as i know, xml.etree doesn't provide a way to get parent.

How can I actually get the node tag?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我只土不豪 2025-02-15 10:15:08

不是很好 - 但它

import xml.etree.ElementTree as ET

xml = '''<r>
<node id="1416646243" />
<node id="1416646244">
    <tag k="crossing" v="unregulated" />
</node>
<node id="1416646245">
    <tag k="crossing" v="traffic_signals" />
</node>
</r>'''

root = ET.fromstring(xml)
node = [n for n in root.findall('.node') if n.find('tag[@v="traffic_signals"]') is not None][0]
print(node.attrib)

起作用

{'id': '1416646245'}

Not very eficcient - but it works

import xml.etree.ElementTree as ET

xml = '''<r>
<node id="1416646243" />
<node id="1416646244">
    <tag k="crossing" v="unregulated" />
</node>
<node id="1416646245">
    <tag k="crossing" v="traffic_signals" />
</node>
</r>'''

root = ET.fromstring(xml)
node = [n for n in root.findall('.node') if n.find('tag[@v="traffic_signals"]') is not None][0]
print(node.attrib)

output

{'id': '1416646245'}
一曲琵琶半遮面シ 2025-02-15 10:15:08

在这里,您的解决方案可以使用“ // parent [./direct_child]”或“ // parent [.//children_of_child]“结果元素”元素是父母,您可以使用子元素检查元素。

root.find('.//node[./tag[@v="traffic_signals"]]')

Here your solution, you can check element with sub-element inside "//parent[./direct_child]" or "//parent[.//children_of_child]" result element will be the parent

root.find('.//node[./tag[@v="traffic_signals"]]')
陌生 2025-02-15 10:15:08

有点骇客,但是您可以使用..在与孩子匹配后返回父母。

root.find('.//node/tag[@v="traffic_signals"]/..')

It's a little hacky, but you can use .. to go back up to the parent after matching the child.

root.find('.//node/tag[@v="traffic_signals"]/..')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文