xml getElementsByTagName w/o recursion?

S

Simon Dahlbacka

Hello,

this is perhaps not directly a python question, but how do I get a
direct child element without going down the tree and possibly find
another element with the same name there?


<foo>
<bar>
<name>This is the interesting part</name>
<baz>
<something>...</something>
<name>this is what I DO NOT want</nameA
</baz>
</bar>
</foo>

I am using xml.dom.minidom and I was thinking along the line of

....
fooNode.childNodes.getNamedNode("name")
....
but that doesn't work..

is the only solution to write an own helper function that iterates the
child nodes and get the correct one?

/Simon
 
B

Bill Rubenstein

Hello,

this is perhaps not directly a python question, but how do I get a
direct child element without going down the tree and possibly find
another element with the same name there?


<foo>
<bar>
<name>This is the interesting part</name>
<baz>
<something>...</something>
<name>this is what I DO NOT want</nameA
</baz>
</bar>
</foo>

I am using xml.dom.minidom and I was thinking along the line of

...
fooNode.childNodes.getNamedNode("name")
...
but that doesn't work..

is the only solution to write an own helper function that iterates the
child nodes and get the correct one?

/Simon
You need to loop through the children of the node and build a list of the nodes
of interest.

Bill R
 
C

Chris Herborth

Simon said:
this is perhaps not directly a python question, but how do I get a
direct child element without going down the tree and possibly find
another element with the same name there?

Install PyXML and use xml.xpath.Evaluate().
<foo>
<bar>
<name>This is the interesting part</name>
<baz>
<something>...</something>
<name>this is what I DO NOT want</nameA
</baz>
</bar>
</foo>

I am using xml.dom.minidom and I was thinking along the line of

...
fooNode.childNodes.getNamedNode("name")
...
but that doesn't work..

# Find all of the <name> children of <bar>:
results = xml.xpath.Evaluate( "/foo/bar/child::name", fooNode )

# xml.xpath.Evaluate() returns a list of results, or []
nameNode = results[0]

Or, if you didn't know what the tags were but you still needed the first
<name> element:

results = xml.xpath.Evaluate( "/descendant::name[position()=1]", fooNode )
nameNode = results[0]

XPath (http://www.w3c.org/TR/xpath) can be a bit tricky to pick up, but it's
_very_ powerful for navigating a DOM tree.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top