如何在提升property_tree前面添加节点
How to add a node in front of boost property_tree
我有一个 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 前面插入新节点?
这是可能的,但它超出了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
期待一对钥匙和self_type
.我对 pair 使用了大括号初始化,对键使用了字符串文字。创建匹配类型的新节点有点棘手,因为使用 value 的构造函数被标记为显式。所以,必须使用它的类型。我用decltype
tree
得到了它.
如果有什么可以简化的,我很乐意欢迎所有改进。
相关文章:
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 移除前面有空格的前2个字符串
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 如何将一个窗口保留在另一个应用程序窗口的前面
- 如何重写全局方法名称以在调用原始方法之前将我的代码推到前面
- 表观调用前面的表达式必须具有指向 func 类型的指针
- 字符数组前面的加号是什么意思?
- 在单链表前面添加一个节点后,我无法遍历每个节点
- ::(范围解析运算符)前面没有任何东西
- 使用 boost::p roperty_tree::p tree 如何获取特定键的值
- 列表C++移动到前面;
- 在每个可变参数宏参数前面加上 C++ 函数参数的名称
- 为什么在函数参数前面添加 const 会出错?
- 增强循环缓冲区push_back在前面插入数据
- 如何计算特定字符前面的字符数
- 有没有办法把字符串数组成员放在".structurevariable"前面?
- 在 Windows 10 中将一个应用程序放在另一个应用程序前面
- 我们可以在队列前面以 O(1) 时间复杂度排队一个元素吗?
- 具有相同名称的方法和内部类(错误:.. 与前面的声明冲突)
- 我必须将 LL 的最后 n 个元素附加到前面