Question

In libxml, I try to select the first element to verify a condition using xpath. If I understood correctly, "//div[contains(@id,'art')][1]" in xpath would give just one element, though I get more than one of them. I use the function getnodeset in the libxml tutorial (see here). Here is the code :

xmlXPathObjectPtr result=getnodeset(def,(xmlChar*) "//div[contains(@id,'art')][1]"); // where def is a htmlDocPtr
xmlNodeSetPtr nodeset;
if(result)
{
nodeset=result->nodesetval;

if(nodeset->nodeNr>1)
    fprintf(stderr,"%i first div with id attribute *art* : %s\n",nodeset->nodeNr,nomDef);
}
Was it helpful?

Solution

Instead of

"//div[contains(@id,'art')][1]"

you want

"(//div[contains(@id,'art')])[1]"

The reason has to do with binding precedence. As you probably know, [1] is shorthand for [position() = 1]. In the variant that you were trying to use, this means "when the current node (the div element) is the first child of its parent". Clearly, there could be many such divs that are each the first child of their respective parent.

When you put parentheses around the expression //div[predicate] and append [1] to that, then you're asking the question you intended to ask: what is the first node in the nodeset selected by //div[predicate]?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top