问题
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