Posted on 2007-03-05 18:46:03-08 by typeszero199
Applying functions to a subtree of document
Hi, I am not sure if I am misunderstanding what I can do with this module, or if something is not working right. Suppose I have this xml document:
<chapter> <sect1> <fig> <caption>blah blah blah</caption> <image/> </fig> </sect1> <sect1> <fig> <no>1-1</no> <caption>cap2</caption> <image/> </fig> </sect1> </chapter>


What I want to do is add the attribute "type" to "fig" elements. If the fig has a <no> child, then it @type="numbered". If not, then "unnumbered".

I am using XML::DOM and XML::DOM::XPath. findnodes is working GREAT for me when selecting from the whole document. To select the fig elements, I simply use my $figlist = findnodes("//fig");.

However, here's where I don't get it. I am looping over $figlist, and using exists() to check if there is a <no> element. i.e. $figlist[$i]->exists("/no").

This doesn't work the way I hoped it would. Am I using it right? In the documentation, it states that we can use these methods to the whole DOM or to a specific node. I was hoping that if I applied exists to a <fig> node, it would look for <no> as a direct child. However, it isn't working that way. For any xpath expression I put in exists, it attempts to evaluate it from the document root, rather than at that point. (If I change the expression to "//no", it always evaluates to true).

My question, can these nodes be evaluated from a specific element, or do they always evaluate from the document root?

Thanks
-Omar
Direct Responses: 4490 | Write a response
Perl Weekly newsletter
A free weekly newsletter for people who are busy to read all the blogs. click here to check it out.