gpt4 book ai didi

c++ - 无法在给定的 xml 文件 libxml2 中正确添加子节点

转载 作者:行者123 更新时间:2023-11-28 08:10:46 24 4
gpt4 key购买 nike

我正在做的是读取一个 xml 文件并尝试将子节点添加到给定的 xml 文件。但问题是,它没有在文件中正确显示,这里是代码:

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 >

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

谁能告诉我我做错了什么?

最佳答案

您的 XML 输出结构没有通过,但要获得正确的缩进,请尝试使用 xmlSaveFormatFile并使用 1 作为 format。在整个 XML 内容之前也调用 xmlKeepBlanksDefault(0),我相信它应该提供您想要的缩进(实际上无法看到您要查找的内容)。

关于c++ - 无法在给定的 xml 文件 libxml2 中正确添加子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9151756/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com