Build a Path for Elementtree Namespaces
Oct 8th, 2009No 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.
class PathBuilder:
def __init__(self,namespace_uri):
self._template=string.Template("{%s}$tag" %namespace_uri)
def all_tags(self,tag):
return "//"+self._template.substitute(tag=tag)
def all_decendents(self,tag):
return ".//"+self._template.substitute(tag=tag)
def children(self,tag):
return self._template.substitute(tag=tag)
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.
