[xml] changing xpath context

Hi all,
I'm having a problem with xpath contexts. Currently I'm using
libxml2-2.4.22. What I want to do is use xpath to find a set of matching
nodes, then for each of those nodes find a set of descendent nodes that
match an xpath. Here's a snippet of code that shows what I'm trying to do:

static void
        xmlDocPtr doc = NULL;
        xmlXPathContextPtr ctx = NULL, ctx2 = NULL;
        xmlXPathObjectPtr pobj = NULL, pobj2 = NULL;
        xmlNodeSetPtr           nset = NULL;
        int i;

        if ((doc = xmlParseFile("try.xml")) == NULL ) {
                printf("parse failed\n");

        ctx = xmlXPathNewContext(doc);

        pobj = xmlXPathEvalExpression("//foo", ctx);
        nset = pobj->nodesetval;
        printf("foo %d\n", nset->nodeNr);
        for (i = 0; i < nset->nodeNr; i++) {
                ctx2 = xmlXPathNewContext(doc);
                ctx2->node = xmlXPathNodeSetItem(nset, i);
                pobj2 = xmlXPathEvalExpression("//bar", ctx2);
                printf("bar %d\n", pobj2->nodesetval->nodeNr);


Basically, I'm trying to find all the nodes matching "//foo". Then, for
each of those nodes, I want to find descendent "bar" nodes. I'm trying to
do this by making an xpath context with the node set to the current "foo"

Here's my sample xml file:

<?xml version="1.0"?>
                <bar/> <bar/>

If I run the program I get:
foo 2
bar 3
bar 3
Which shows that //bar is searching from the document root rather than the
current "foo" node.

I think this should be a valid use of xpath. Am I doing something wrong?


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]