使用pugixml和c++在.xml中添加行

Add line to .xml using pugixml and C++

本文关键字:xml 添加行 c++ pugixml 使用      更新时间:2023-10-16

我有一个XML文档,我需要使用pugixml和Cpp编写。我的XML文档的一部分看起来像这样:

line 4                   <people>
line 5                   <guys>
line 6                   <dude name="man" delay="1" life="0.75" score="5" />
line 7                   <dude name="man" delay="1" life="0.75" score="5" />
line 8                   <dude name="man" delay="1" life="0.75" score="5" />
line 9                   <dude name="man" delay="1" life="0.75" score="5" />
line 10                  <dude name="man" delay="1" life="0.75" score="5" />
line 11                  </guys>
line 12                   <guys>
line 13                   <dude name="man" delay="1" life="0.75" score="5" />
line 14                   <dude name="man" delay="1" life="0.75" score="5" />
line 15                   <dude name="man" delay="1" life="0.75" score="5" />
line 16                   <dude name="man" delay="1" life="0.75" score="5" />
line 17                  <dude name="man" delay="1" life="0.75" score="5" />
line 18                  </guys>
                         </people>

我如何在第13行之后添加另一行(dude name="man" delay="1" life="0.75" score="5"),将我的.xml文件中的所有其他行向下移动一行?

我正在尝试....

//get xml object
  pugi::xml_document doc;
//load xml file
  doc.load_file(pathToFile.c_str);
//edit file
  doc.child("people").child("guys").append_copy(doc.child("people").child("guys").child("dude"));
//save file
doc.save_file(pathToFile.c_str);

但它似乎不起作用。什么好主意吗?

使用XPath,它变得更加容易和易读,没有所有的child()函数调用。

插入到第一行移动下面所有的行使用prepend_copy函数

这适用于您的示例xml:

pugi::xml_document doc;
//load xml file
doc.load_file(pathToFile);
pugi::xpath_node nodeToInsert;
pugi::xpath_node nodeParent;
try
{
    nodeToInsert = doc.select_single_node("/people/guys[2]/dude[1]");
    nodeParent = doc.select_single_node("/people/guys[2]");
}
catch (const pugi::xpath_exception& e)
{
    cerr << "error " << e.what() << endl;
    return -1;
}
nodeParent.node().prepend_copy(nodeToInsert.node()); // insert at the first row
//save file
std::cout << "Saving result: " << doc.save_file("output.xml") << std::endl;