Python:使用minidom搜索具有特定文本的节点

发布于 2024-07-16 00:26:49 字数 136 浏览 4 评论 0原文

我目前面临的 XML 看起来像这样:

<ID>345754</ID>

它包含在层次结构中。 我已经解析了 xml,并希望通过搜索“345754”找到 ID 节点。

I am currently faced with XML that looks like this:

<ID>345754</ID>

This is contained within a hierarchy. I have parsed the xml, and wish to find the ID node by searching on "345754".

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

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

发布评论

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

评论(2

热鲨 2024-07-23 00:26:49

vartec 的答案需要更正(抱歉,我不确定我能做到这一点),它应该是这样的:有

xmldoc = xml.dom.minidom.parse('your.xml')
matchingNodes = [node for node in xmldoc.getElementsByTagName("ID") if 
node.firstChild.nodeValue == '345754']

两件事是错误的:(i)标签名称区分大小写,因此匹配 "id" 获胜不起作用,并且 (ii) 对于元素节点 .nodeValue 将为 None,您需要访问包含所需值的元素节点内部的文本节点。

vartec's answer needs correcting (sorry I'm not sure I can do that), it should read:

xmldoc = xml.dom.minidom.parse('your.xml')
matchingNodes = [node for node in xmldoc.getElementsByTagName("ID") if 
node.firstChild.nodeValue == '345754']

Two things were wrong with it: (i) tag names are case sensitive so matching on "id" won't work and (ii) for an element node .nodeValue will be None, you need access to the text nodes that is inside the element node which contains the value you want.

べ映画 2024-07-23 00:26:49
xmldoc = minidom.parse('your.xml')
matchingNodes = [node for node in xmldoc.getElementsByTagName("id") if node.nodeValue == '345754']

另请参阅:

xmldoc = minidom.parse('your.xml')
matchingNodes = [node for node in xmldoc.getElementsByTagName("id") if node.nodeValue == '345754']

See also:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文