Python: Using minidom to search for nodes with a certain text

做~自己de王妃 提交于 2019-12-11 01:07:32

问题


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".


回答1:


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

See also:

  • How to get whole text of an Element in xml.minidom?
  • All nodeValue fields are None when parsing XML



回答2:


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.



来源:https://stackoverflow.com/questions/706453/python-using-minidom-to-search-for-nodes-with-a-certain-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!