[英]How to insert a new node in a xml_document using RapidXml for C++ using strings?
std::string src = "<xml><node1>aaa</node1><node2>bbb</node2><node1>ccc</node1></xml>";
std::string src2 = "<nodex>xxx</nodex>";
我想使用RapidXml將src2中的節點附加到src中的樹中我執行此操作:
xml_document<> xmldoc;
xml_document<> xmlseg;
std::vector<char> s(src.begin(), src.end());
std::vector<char> x(src2.begin(), src2.end());
xmldoc.parse<0>(&s[0]);
xmlseg.parse<0>(&x[0]);
xml_node<>* a = xmlseg.first_node(); /* Node to append */
xmldoc.first_node("xml")->append_node(a); /* Appending node a to the tree in src */
好吧,它很好編譯,但在運行時我遇到了這個可怕的錯誤:
void rapidxml :: xml_node :: append_node(rapidxml :: xml_node *)[with Ch = char]:斷言`child &&!child-> parent()&& child-> type()!= node_document'失敗。 中止
我不知道該怎么做。 問題很簡單我需要將一個節點附加到樹(xml),但我有字符串。
我想這是因為我試圖將一個樹的節點插入到另一個樹中......只有為給定樹分配的節點才能添加到該樹中......這很糟糕......
有沒有辦法以簡單的方式做我需要的東西?
謝謝。
#include <iostream>
#include <string>
#include <vector>
#include <rapidxml.hpp>
#include <rapidxml_print.hpp>
int main(){
std::string src = "<xml><node1>aaa</node1><node2>bbb</node2><node1>ccc</node1></xml>";
std::string src2 = "<nodex><nodey>xxx</nodey></nodex>";
//std::string src2 = "<nodex>xxx</nodex>";
rapidxml::xml_document<> xmldoc;
rapidxml::xml_document<> xmlseg;
std::vector<char> s( src.begin(), src.end() );
s.push_back( 0 ); // make it zero-terminated as per RapidXml's docs
std::vector<char> x(src2.begin(), src2.end());
x.push_back( 0 ); // make it zero-terminated as per RapidXml's docs
xmldoc.parse<0>( &s[ 0 ] );
xmlseg.parse<0>( &x[0] );
std::cout << "Before:" << std::endl;
rapidxml::print(std::cout, xmldoc, 0);
rapidxml::xml_node<>* a = xmlseg.first_node(); /* Node to append */
rapidxml::xml_node<> *node = xmldoc.clone_node( a );
//rapidxml::xml_node<> *node = xmldoc.allocate_node( rapidxml::node_element, a->name(), a->value() );
xmldoc.first_node("xml")->append_node( node ); /* Appending node a to the tree in src */
std::cout << "After :" << std::endl;
rapidxml::print(std::cout, xmldoc, 0);
}
輸出:
<xml>
<node1>aaa</node1>
<node2>bbb</node2>
<node1>ccc</node1>
</xml>
After :
<xml>
<node1>aaa</node1>
<node2>bbb</node2>
<node1>ccc</node1>
<nodex>
<nodey>xxx</nodey>
</nodex>
</xml>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.