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.
The XML file you’re generating is this:
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.