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

P

provowallis

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.

Thanks,

Provo

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]
 
U

uche.ogbuji

provowallis said:
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.
 

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

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top