0
我正在做的是讀取xml文件並嘗試將子節點添加到給定的xml文件。但問題是,它不能正常顯示此文件中的代碼如下:無法在給定的xml文件中正確添加子節點,libxml2
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);
而且給出的xml文件的結構是
< ?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>
,並使用我的代碼的XML後顯示的內容在下面的格式
< ?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>
主要問題是它沒有添加適當的縮進的子節點。
任何人都可以告訴我我做錯了什麼?