views:

600

answers:

2

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

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

See also:

vartec
I'm fairly sure that won't work - have you tested it? nodeValue is usually set to 'None' on element nodes (as one of your links says). I've never found it any use - one has to drill down to the text node children.
Francis Davey
+1  A: 

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.

Francis Davey