[英]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.