What I am doing is reading a xml file and trying to add a child node to a given xml file. But the problem is, it is not showing properly in the file here is the code:
xmlDocPtr doc;
xmlNodePtr nodeptr=NULL , node = NULL , node_child =NULL;
doc = xmlParseFile("Mainfile.xml");
if (doc == NULL ) {
fprintf(stderr,"Document not parsed successfully. \n");
return;
}
nodeptr = xmlDocGetRootElement(doc);
if (nodeptr == NULL) {
fprintf(stderr,"empty document\n");
xmlFreeDoc(doc);
return;
}
if (xmlStrcmp(nodeptr->name, (const xmlChar *) "story")) {
fprintf(stderr,"document of the wrong type, root node != story");
xmlFreeDoc(doc);
return;
}
node = xmlNewNode( NULL, BAD_CAST "Account" );
xmlNewProp(node, BAD_CAST "id", BAD_CAST "A001");
xmlAddChild(nodeptr , node);
node_child = xmlNewChild(node, NULL, BAD_CAST "Country",BAD_CAST "US");
xmlAddChild(node,node_child);
xmlAddChild(nodeptr , node);
node_child = xmlNewChild(node, NULL, BAD_CAST "City", BAD_CAST "ABC");
xmlAddChild(node,node_child);
xmlAddChild(nodeptr , node);
node_child = xmlNewChild(node, NULL, BAD_CAST "ZIP",BAD_CAST "34040");
xmlAddChild(node,node_child);
xmlAddChild(nodeptr , node);
xmlSaveFile("Mainfile.xml", doc);
xmlFree(doc);
And the structure of given xml file is
< ?xml version="1.0"? >
< Project >
< author >John Fleck< /author >
< datewritten >June 2, 2002< /datewritten >
< keyword >example keyword< /keyword >
< Account id = "A000" >
< Country >UK< /Country >
< City >XYZ< /City >
< Zip >67688< /Zip >
< /Account >
< /Project >
and after using my code the xml showing the content in below format
< ?xml version="1.0"? >
< Project >
< author >John Fleck< /author >
< datewritten >June 2, 2002</datewritten>
< keyword >example keyword< /keyword >
< Account id = "A000" >
< Country >UK< /Country >
< City >XYZ< /City >
< Zip >67688< /Zip >
< /Account >
< Account id = "A001" >< Country >US< /Country >< City >ABC< /City >< Zip >34040< /Zip >< /Account >< /Project >
The main problem is it is not adding the child node with proper indentation.
Can anyone suggest me what I'm doing wrong?
The structure of your XML output didn't come through, but to get proper indentation, try using xmlSaveFormatFile
and use 1 for the format
. Also call xmlKeepBlanksDefault(0)
before your whole XML stuff and I believe it should give the indentation you want (without actually being able to see what you're looking for).