xml getElementsByTagName w/o recursion?
Chris Herborth
chrish at cryptocard.com
Wed Feb 11 09:47:29 EST 2004
Simon Dahlbacka wrote:
> 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.
--
Chris Herborth chrish at cryptocard.com
Documentation Overlord, CRYPTOCard Corp. http://www.cryptocard.com/
Never send a monster to do the work of an evil scientist.
More information about the Python-list
mailing list