Where Are The Wise Men?

Mike's Ramblings

Build a Path for Elementtree Namespaces

| Comments

I really like using [ElementTree][]and it's [lxml][]and [xml.etree][] brethern. But one of my pet peeves is[how it deals with namespaces.][]I understand the reasoning -- it's just difficult and bulky. Combining the syntax of {namespace-uri} with [an XPath-like search string][]can be confusing.

I'm muddling over this while I'm writing yet another utility script to help me with some XML. I stop and decided I'm going to build a help class, wittingly called PathBuilder.

[python]
class PathBuilder:

def __init__(self,namespace_uri):

self._template=string.Template("{%s}$tag" %namespace_uri)

return "//"+self._template.substitute(tag=tag)

return ".//"+self._template.substitute(tag=tag)

def children(self,tag):

return self._template.substitute(tag=tag)

[/python]

My methods above are all that I need at this point, but you can see how to build them all. I can put all my path building knowledge in that class and then just tell it what I want and it will give it to me.