user856358
user856358

Reputation: 593

Search for an XML node in a parent by string with python

I'm working with python xml.dom. I'm looking for a particular method that takes in a node and string and returns the xml node that is is named string. I can't find it in the documentation

I'm thinking it would work something like this

nodeObject =parent.FUNCTION('childtoFind')

where the nodeObject is under the parent

Or barring the existence of such a method, is there a way I can make the string a node object?

Upvotes: 0

Views: 88

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123970

You are looking for the .getElementsByTagname() function:

nodeObjects = parent.getElementsByTagname('childtoFind')

It returns a list; if you need only one node, use indexing:

nodeObject = parent.getElementsByTagname('childtoFind')[0]

You really want to use the ElementTree API instead, it's easier to use. Even the minidom documentation makes this recommendation:

Users who are not already proficient with the DOM should consider using the xml.etree.ElementTree module for their XML processing instead.

The ElementTree API has a .find() function that let's you find the first matching descendant:

element = parent.find('childtoFind')

Upvotes: 1

Related Questions