0

I simply want to read the string in the content of XML Nodes which I wrote out a file before. Here is the code:

int main() {

xmlNodePtr n, n2, n3;
xmlDocPtr doc;
xmlChar *xmlbuff;
int buffersize;
xmlChar* key;

doc = xmlNewDoc(BAD_CAST "1.0");
n = xmlNewNode(NULL, BAD_CAST "root");


xmlNodeSetContent(n, BAD_CAST "test1");
n2 = xmlNewNode(NULL, BAD_CAST "devices");
xmlNodeSetContent(n2, BAD_CAST "test2");
n3 = xmlNewNode(NULL, BAD_CAST "device");
xmlNodeSetContent(n3, BAD_CAST "test3");

//n2 = xmlDocCopyNode(n2, doc, 1);
xmlAddChild(n2,n3);
xmlAddChild(n,n2);


xmlDocSetRootElement(doc, n);


xmlSaveFormatFileEnc( FILENAME, doc, "utf-8", 1 );

doc = xmlParseFile(FILENAME);
n = xmlDocGetRootElement(doc);

key = xmlNodeListGetString(doc, n, 1);
printf("keyword: %s\n", key);
xmlFree(key);

n = n->children;

key = xmlNodeListGetString(doc, n, 1);
printf("keyword: %s\n", key);
xmlFree(key);

n = n->children;

key = xmlNodeListGetString(doc, n, 1);
printf("keyword: %s\n", key);
xmlFree(key);

n2 = xmlNewNode(NULL, BAD_CAST "address");
xmlAddChild(n,n2);

xmlDocSetRootElement(doc, n);

xmlSaveFormatFileEnc( FILENAME, doc, "utf-8", 1 );

return 0;
}

Output of this code is -> keyword: (null) keyword: test1 keyword: (null)

Why can't I read test2 and test3?

Thanks in advance.

bfaskiplar
  • 865
  • 1
  • 7
  • 23

1 Answers1

1

The XML file you're generating is this:

<?xml version="1.0" encoding="utf-8"?>
<root>
    test1
    <devices>
        test2
        <device>
            test3
        </device>
    </devices>
</root>

In libxml, children contain both the text nodes and the elements. You need to check for the type field to know what a node points to.

Here's the code you can use (I'm sure there are better ways to do this, but it clearly shows the type tests you should perform). I'm using n for the element nodes and n2 for the search for text nodes.

// Get <root>    
n = xmlDocGetRootElement(doc);
n2 = n -> children;
while (n2 != NULL && n2 -> type != XML_TEXT_NODE)
    n2 = n2 -> next;
if (n2 != NULL)
{
   key = xmlNodeListGetString(doc, n2, 1);
   printf("keyword: %s\n", key);
   xmlFree(key);
}

// grab child
n = n -> children;
while (n != NULL && n -> type != XML_ELEMENT_NODE)
    n = n -> next;
if (n == NULL)
    return -1;

// grab its 1st text child       
n2 = n -> children;
while (n2 != NULL && n2 -> type != XML_TEXT_NODE)
    n2 = n2 -> next;
if (n2 != NULL)
{
   key = xmlNodeListGetString(doc, n2, 1);
   printf("keyword: %s\n", key);
   xmlFree(key);
}

// grab child
n = n -> children;
while (n != NULL && n -> type != XML_ELEMENT_NODE)
    n = n -> next;
if (n == NULL)
    return -1;

// grab its 1st text child       
n2 = n -> children;
while (n2 != NULL && n2 -> type != XML_TEXT_NODE)
    n2 = n2 -> next;
if (n2 != NULL)
{
   key = xmlNodeListGetString(doc, n2, 1);
   printf("keyword: %s\n", key);
   xmlFree(key);
}
BxlSofty
  • 501
  • 4
  • 16