How to insert a new node into 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>";
I want to add node in src2 inside the tree in src using RapidXml I do this:
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 */
Ok, it compiles fine, but on startup I got this terrible error:
void rapidxml :: xml_node :: append_node (rapidxml :: xml_node *) [with Ch = char]: Statement `child && &! child-> parent () && child-> type ()! = node_document 'failed. Canceled
I do not know how to do that. The problem is simple: I need to add node to the tree (xml), but I have lines.
I assume this is happening because I am trying to insert a tree node into another tree ... only the nodes allocated for this tree can be added to this tree ... it sucks ...
, , ?
.
#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 docs
std::vector<char> x(src2.begin(), src2.end());
x.push_back( 0 ); // make it zero-terminated as per RapidXml 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>