2012-02-05 51 views
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>  

主要问题是它没有添加适当的缩进的子节点。

任何人都可以告诉我我做错了什么?

回答

1

您的XML输出的结构没有通过,但要获得正确的缩进,请尝试使用xmlSaveFormatFile并将1用于format。在你的整个XML文件之前也要调用xmlKeepBlanksDefault(0),我相信它应该给你想要的缩进(没有真正能够看到你在找什么)。