I am trying to parse an xml file from my program. I am able to get the rootnode and print its name, property etc. successfully( No hardwork, only an api call :) ). But when I try to read its childnode and print its name, I am not getting what is there in the xml.
Here is my xml file
<?xml version ="1.0" encoding ="UTF-8" ?>
<LanguageStats>
<Languages>
<Language name="C">
<extensions key="c"/>
<color key="\x1b[33m"/>
</Language>
</Languages>
</LanguageStats>
Here is my C code
#include <stdio.h>
#include <unistd.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#define XML_CFG_FILE "./lang_list.xml"
static void parse_xml(xmlNode* root_node)
{
xmlNode *curr_node = NULL;
if( root_node != NULL )
{
printf("\nRoot Element %s", root_node->name);
curr_node = root_node->children;
printf("\nCurrent Element %s", curr_node->name);
curr_node = curr_node->children;
if( !curr_node )
{
printf(" Something is wrong");
}
}
else
{
printf("Root Element NULL");
}
}
int main()
{
xmlDoc *doc = NULL;
xmlNode *root_element = NULL;
LIBXML_TEST_VERSION
if( ( doc = xmlReadFile( XML_CFG_FILE, NULL, 0)) == NULL )
{
printf("error: could not parse file %s\n", XML_CFG_FILE);
exit(-1);
}
root_element = xmlDocGetRootElement(doc);
parse_xml(root_element);
return 0;
}
I am getting this below output.
Root Element LanguageStats
Current Element text Something is wrong
When I change the logic to
printf("\nRoot Element %s", root_node->name);
curr_node = root_node->children;
printf("\nCurrent Element %s", curr_node->name);
curr_node = curr_node->next;
printf("\nCurrent Element %s", curr_node->name);
my output becomes
Root Element LanguageStats
Current Element text
Current Element Languages
My question is Am I missing something? or does libxml always work like that?. This is bugging me a lot and I am not able to solve this. Any small tips would be appreciated
I figured how to get the next Element. Here, I am attaching the code snippet
static xmlNode* GetNextNode(const xmlNode* node )
{
xmlNode* ret_node = node->next;
while( ret_node )
{
/* Node has type XML_ELEMENT_NODE, if it has property to hold children */
if( ret_node->type != XML_ELEMENT_NODE )
{
ret_node = ret_node->next;
}
else
{
printf("Found element node %s\n", ret_node->name );
break;
}
}
return ret_node;
}
This somehow worked for me.