Search code examples
cxml-parsinglibxml2

Finding a node in xml file with libxml2


I am trying to write a function that will find a node with a specified name in a xml file. The problem is that the function never finds the specified node.

xmlNodePtr findNodeByName(xmlNodePtr rootnode, const xmlChar * nodename)
{
    xmlNodePtr node = rootnode;
    if(node == NULL){
        log_err("Document is empty!");
        return NULL;
    }

    while(node != NULL){

        if(!xmlStrcmp(node->name, nodename)){
            return node; 
        }
        else if(node->children != NULL){
            node = node->children; 
            xmlNodePtr intNode =  findNodeByName(node, nodename); 
            if(intNode != NULL){
                return intNode;
            }
        }
        node = node->next;
    }
    return NULL;
}

I can see in the debugger that function does go deep into the sub nodes but still returns NULL.

Thanks in advance.


Solution

  • Your function is correct. Add a debugging line to see why it doesn't work in your case. For example:

        printf("xmlStrcmp(%s, %s)==%d\n", node->name, nodename,
            xmlStrcmp(node->name, nodename));
    

    But you don't really need that function. You may use xmlXPathEval.