I want to add the element in the xml file. Can anyone help me to do that?
Following is my code tryout.
<?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>
code:
if (doc.LoadFile()) {
TiXmlHandle docHandle(&doc);
TiXmlElement* fileLog = docHandle.FirstChild("category1").ToElement();
if (fileLog) {
TiXmlElement newCategory2("category2");
newCategory2.SetAttribute("name", "5");
fileLog->InsertEndChild(newCategory2);
}
}
Hope to get help from anyone.
TiXML does not accept spaces between XMLs tags as </category2 >
, it must be </category2>
. Your LoadFile will return false and the node will not be inserted.
This following code works as expected :
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);
}
Output:
<?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>