2015-08-13 16 views
0

我有一個需要使用pugixml和Cpp編寫的XML文檔。我的XML文檔的一部分是這樣的:使用pugixml和C++將行添加到.xml

line 4     <people> 
line 5     <guys> 
line 6     <dude name="man" delay="1" life="0.75" score="5" /> 
line 7     <dude name="man" delay="1" life="0.75" score="5" /> 
line 8     <dude name="man" delay="1" life="0.75" score="5" /> 
line 9     <dude name="man" delay="1" life="0.75" score="5" /> 
line 10     <dude name="man" delay="1" life="0.75" score="5" /> 
line 11     </guys> 
line 12     <guys> 
line 13     <dude name="man" delay="1" life="0.75" score="5" /> 
line 14     <dude name="man" delay="1" life="0.75" score="5" /> 
line 15     <dude name="man" delay="1" life="0.75" score="5" /> 
line 16     <dude name="man" delay="1" life="0.75" score="5" /> 
line 17     <dude name="man" delay="1" life="0.75" score="5" /> 
line 18     </guys> 
         </people> 

如何將添加13號線陸續(花花公子名=「人」延遲=「1」的生活=「0.75」得分=「5」)專線,搬家所有其他行在我的.xml文件中一個下降?

我想....

//get xml object 
    pugi::xml_document doc; 
//load xml file 
    doc.load_file(pathToFile.c_str); 
//edit file 
    doc.child("people").child("guys").append_copy(doc.child("people").child("guys").child("dude")); 
//save file 
doc.save_file(pathToFile.c_str); 

但它似乎並不奏效。有任何想法嗎?

+1

目前尚不清楚如何[文件](http://pugixml.org/docs/manual.html)已經讓你失望。你有沒有注意到右邊的目錄? –

+0

是的,我一直在閱讀它,但仍不知道如何才能讓它適應我的情況。你能提供一個例子嗎? – ctapp1

回答

1

使用XPath它變得更容易和可讀,沒有child()函數調用。

要在第一行中插入移動下面的所有其他行,請使用prepend_copy函數。

此作品在這裏與您的示例XML:

pugi::xml_document doc; 

//load xml file 
doc.load_file(pathToFile); 

pugi::xpath_node nodeToInsert; 
pugi::xpath_node nodeParent; 

try 
{ 
    nodeToInsert = doc.select_single_node("/people/guys[2]/dude[1]"); 
    nodeParent = doc.select_single_node("/people/guys[2]"); 
} 

catch (const pugi::xpath_exception& e) 
{ 
    cerr << "error " << e.what() << endl; 
    return -1; 
} 

nodeParent.node().prepend_copy(nodeToInsert.node()); // insert at the first row 

//save file 
std::cout << "Saving result: " << doc.save_file("output.xml") << std::endl; 
+0

工作就像一個魅力。非常感激 – ctapp1