我想在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);
}
}
希望从任何人那里获得帮助。
答案 0 :(得分:1)
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>