Trying to find a elements Xpath and store it as a attribute

uche.ogbuji at gmail.com uche.ogbuji at gmail.com
Fri Oct 6 14:38:32 EDT 2006


provowallis wrote:
> Hi all,
>
> I've been struggling with this for a while so I'm hoping that someone
> could point me in the right direction. Here's my problem: I'm trying to
> get the XPath for a given node in my document and then store that XPath
> as an attribute of the element itself. If anyone has a recommendation
> I'd be happy to hear it.


Sorry.  I only check c.l.py once a week or so...

> For instance, I would take this XML
>
> ###before
>
> <?xml version="1.0"?>
> <hello-world>
> <greeter>An XSLT Programmer</greeter>
> <greeting>Hello, World!</greeting>
> </hello-world>
>
> ###after
>
> <?xml version="1.0"?>
> <hello-world>
> <greeter xp="hello-word[1]/greeter[1]">An XSLT Programmer</greeter>
> <greeting xp="hello-world[1]/greeting[1]">Hello, World!</greeting>
> </hello-world>
>
> ###
>
> import sets
> import amara
> from amara import binderytools
>
> doc = amara.parse('hello.xml')
> elems = {}
>
> for e in doc.xml_xpath('//*'):
>
>      paths = elems.setdefault((e.namespaceURI, e.localName),
> sets.Set())
>      path = u'/'.join([n.nodeName for n in
> e.xml_xpath(u'ancestor::*')])
>      paths.add(u'/' + path)
>
> for name in elems:
>
>      doc.name.km = elems[name]

It's a tougher problem than you may think :-)

Luckily it's a problem I've worked on.  For discussion see:

http://www.xml.com/pub/a/2004/11/24/py-xml.html

For an updated solution see abs_path in Amara domtools.  In most cases
you can safely call that on an Amara bindery node.


--
Uche Ogbuji                               Fourthought, Inc.
http://uche.ogbuji.net                    http://fourthought.com
http://copia.ogbuji.net                   http://4Suite.org
Articles: http://uche.ogbuji.net/tech/publications/




More information about the Python-list mailing list