gpt4 book ai didi

c++ - 插入元素 (TinyXml)

转载 作者:行者123 更新时间:2023-11-30 04:54:03 27 4
gpt4 key购买 nike

我想在 xml 文件中添加元素。谁能帮我做到这一点?

以下是我的代码试用。

 <?xml version="1.0" encoding="UTF-8" ?>
<category1>
<category2 name="1">1.79639 0.430521</category2 >
<category2 name="2">2.06832 0.652695</category2 >
<category2 name="3">1.23123 0.111212</category2 > <-- new
</category1>

代码:

 if (doc.LoadFile()) {
TiXmlHandle docHandle(&doc);
TiXmlElement* fileLog = docHandle.FirstChild("category1").ToElement();
if (fileLog) {
TiXmlElement newCategory2("category2");
newCategory2.SetAttribute("name", "5");
fileLog->InsertEndChild(newCategory2);
}
}

希望得到大家的帮助。

最佳答案

TiXML 不接受 XML 标签之间的空格作为 </category2 > , 它必须是 </category2> .您的 LoadFile 将返回 false,并且不会插入该节点。

以下代码按预期工作:

    const char * szTiXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
"<category1>"
"<category2 name=\"1\">1.79639 0.430521</category2>"
"<category2 name=\"2\">2.06832 0.652695</category2>"
"<category2 name=\"3\">1.23123 0.111212</category2>"
"</category1>";

TiXmlDocument doc;
doc.Parse( szTiXML );
//if (doc.LoadFile())
{
TiXmlHandle docHandle(&doc);
TiXmlElement* fileLog = docHandle.FirstChild("category1").ToElement();
if (fileLog) {
TiXmlElement newCategory2("category2");
TiXmlText myText("Hello From SO");

newCategory2.SetAttribute("name", "5");
newCategory2.InsertEndChild(myText);

fileLog->InsertEndChild(newCategory2);
}

doc.Print(stdout);
}

输出:

<?xml version="1.0" encoding="UTF-8" ?>
<category1>
<category2 name="1">1.79639 0.430521</category2>
<category2 name="2">2.06832 0.652695</category2>
<category2 name="3">1.23123 0.111212</category2>
<category2 name="5">Hello From SO</category2>
</category1>

关于c++ - 插入元素 (TinyXml),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53723795/

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