如何在提升property_tree前面添加节点

How to add a node in front of boost property_tree

本文关键字:tree 前面 添加 节点 property      更新时间:2023-10-16

我有一个 xml

<MyXML>
<Tag2>2</Tag2>
<Tag3>3</Tag2>
<Tag4>4</Tag3>
</MyXML>

并将其读入 boost::p roperty_tree::p tree XML根 使用 boost::p roperty_tree::read_xml

现在,如果我通过以下方式添加一个新节点

xmlroot.add("MyXML.Tag1", "1");

此新节点将添加到现有标记的背面。提升后::p roperty_tree::write_xml,我得到

<MyXML>
<Tag2>2</Tag2>
<Tag3>3</Tag2>
<Tag4>4</Tag3>
<Tag1>1</Tag1>
</MyXML>

有没有办法在 Tag2 前面插入新节点?

这是可能的,但它超出了getadd等标准访问器的范围,因此必须采用更长、更繁琐的迭代器方式。基本上,您需要为节点获取一个迭代器并使用insertpush_front在所需位置插入一个新节点。

完整示例:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <string>
#include <exception>
#include <iostream>
namespace pt = boost::property_tree;
int main()
{
try
{
std::string xml_content =
"<MyXML> 
<Tag2>2</Tag2> 
<Tag3>3</Tag2> 
<Tag4>4</Tag3> 
</MyXML>";
std::stringstream xml (xml_content);
pt::ptree tree;
pt::read_xml (xml, tree);
/* ~~~~ KEY STUFF ~~~~ */
auto root = tree.find("MyXML");
root->second.push_front({"NewTag", decltype(tree)("1")});
/* ~~~~ KEY STUFF ~~~~ */
pt::write_xml (std::cout, tree);
}
catch (std::exception &e)
{
std::cout << "Error: " << e.what() << "n";
}
return 0;
}

关键内容解释:

auto root = tree.find("MyXML");
root->second.push_front({"NewTag", decltype(tree)("1")});

好的,所以第一行是不费吹灰之力的,我们需要获取我们的"工作"节点。

第二行使用push_front,在调用方的前面插入一个新节点。但是 out 调用者位于迭代器的second字段,这是find("MyXML")的结果。

然后push_front期待一对钥匙和self_type.我对 pair 使用了大括号初始化,对键使用了字符串文字。创建匹配类型的新节点有点棘手,因为使用 value 的构造函数被标记为显式。所以,必须使用它的类型。我用decltypetree得到了它.

如果有什么可以简化的,我很乐意欢迎所有改进。