[xml] changing xpath context
- From: Joe Eggleston <joe arbor net>
- To: xml gnome org
- Subject: [xml] changing xpath context
- Date: Tue, 3 Dec 2002 19:21:48 -0500 (EST)
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
try(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");
exit(1);
}
xmlXPathInit();
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);
xmlXPathFreeObject(pobj2);
xmlXPathFreeContext(ctx2);
}
xmlXPathFreeObject(pobj);
xmlFreeDoc(doc);
}
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"
node.
Here's my sample xml file:
<?xml version="1.0"?>
<doc>
<foo>
<bar/>
</foo>
<foo>
<bar/> <bar/>
</foo>
</doc>
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?
Thanks,
Joe
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]