【问题标题】:Add line to .xml using pugixml and C++使用 pugixml 和 C++ 将行添加到 .xml
【发布时间】:2015-11-06 20:24:54
【问题描述】:

我有一个需要使用 pugixml 和 Cpp 写入的 XML 文档。我的部分 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);

但它似乎不起作用。有什么想法吗?

【问题讨论】:

  • 不清楚the documentation 是如何让你失望的。你注意到右边的目录了吗?
  • 是的,我一直在阅读它,但仍然不确定如何让它适应我的情况。你能举个例子吗?

标签: c++ xml xml-parsing pugixml


【解决方案1】:

使用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;

【讨论】:

  • 工作就像一个魅力。非常感谢
猜你喜欢
  • 1970-01-01
  • 2010-12-16
  • 2011-09-01
  • 2023-03-20
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多