2011-01-12 49 views
3
std::string src = "<xml><node1>aaa</node1><node2>bbb</node2><node1>ccc</node1></xml>"; 
std::string src2 = "<nodex>xxx</nodex>"; 

我想用RapidXml 到節點追加在SRC2樹裏面的src我這樣做:如何使用RapidXml for C++使用字符串在xml_document中插入新節點?

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]: Assertion `child && !child->parent() && child->type() != node_document' failed. Aborted

我不知道該怎麼辦。 問題很簡單我需要將一個節點附加到樹(xml),但我有字符串。

我想這是因爲我想插入一個樹的節點到另一個樹...只有節點分配一個給定的樹可以被添加到該樹......這吮吸......

有沒有辦法以一種簡單的方式來做我所需要的?

謝謝。

回答

3
#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> 
+0

謝謝你的答案,但工作是肯定的。我需要解析兩個字符串才能獲得兩個節點。我不能錯過這兩個要求中的任何一個。分配節點使他們成爲我想要追加的子節點,並且該示例有效,但這不是我的情況。對不起。無論如何,感謝您的幫助:) – Andry 2011-01-13 00:37:44

相關問題