[英]How to add a node in front of boost property_tree
我有一个XML
<MyXML>
<Tag2>2</Tag2>
<Tag3>3</Tag2>
<Tag4>4</Tag3>
</MyXML>
并使用boost :: property_tree :: read_xml将其读入boost :: property_tree :: ptree xmlroot
现在,如果我添加一个新节点
xmlroot.add("MyXML.Tag1", "1");
这个新节点将添加到现有标签的后面。 在boost :: property_tree :: write_xml之后,我得到了
<MyXML>
<Tag2>2</Tag2>
<Tag3>3</Tag2>
<Tag4>4</Tag3>
<Tag1>1</Tag1>
</MyXML>
有没有办法在Tag2前面插入新节点?
这是可能的,但是它超出了get
和add
类的标准访问器的范围,因此必须采用更长,更麻烦的迭代器方式。 基本上,您需要为节点获取一个迭代器,并使用insert
或push_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
需要一对key和self_type
。 我对使用大括号初始化,对键使用字符串文字。 创建一个匹配类型的新节点会有些棘手,因为使用value的构造函数被标记为显式的。 因此,必须使用它的类型。 我使用tree
decltype
来获取它。
如果可以简化任何事情,我很高兴欢迎所有改进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.