2012-04-22 61 views
1

我正在向XML文件寫入一組結果。每個結果集都包含一系列結果。我的問題是(在代碼的幾次執行過程中),當我嘗試將一些結果寫入一組結果時,XML解析器獲取現有XML文件中的第一個(頂部)結果集,並將結果附加到該結果(舊)集。例如:將子節點添加到XML結構的頂部。提升屬性樹

<root> 
    <result_set result_number="0"> <--- Parser selects this result set 
    <result number="0"> 
     <tolerance>100</tolerance> 
    </result> 
    <result number="1"> 
     <tolerance>100</tolerance> 
    </result> 
    <resultnumber="0">   <---- This should be added to result set 1  
     <tolerance>100</tolerance> 
    </result> 
    </result_set> 
    <result_set result_number="1"/> <-- New result set added to Xml, missing results 
</root> 

因此,我想知道是否有可能將最新結果集寫入到XML文件的頂部?或者,當檢索最新的結果集時,獲取列表中的最後一個結果集?

我希望我已經清楚地解釋了我自己。 感謝

(示例代碼我使用)

void initialise(std::string filename) 
{ 
    ptree pt; 
    xml_writer_settings<char> w('\t', 1); 
    read_xml(filename, pt, boost::property_tree::xml_parser::trim_whitespace); 
    std::ofstream xmlFile(filename.c_str(), std::ios::out); 

    // Probably not the best way to check for a root node 
    try 
    { 
    ptree & rootNode = pt.get_child("root"); 
    } 
    catch(...) 
    { 
    xmlFile << "<root></root>" << std::endl; 
    read_xml(filename, pt, boost::property_tree::xml_parser::trim_whitespace); 
    } 


    ptree & rootNode = pt.get_child("root"); 
    ptree resultSetNode; 
    resultSetNode.add("<xmlattr>.result_number", 0); 
    rootNode.add_child("result_set", resultSetNode); 
    write_xml(filename, pt, std::locale(), w); 

} 

void save1(std::string filename) 
{ 
    ptree pt; 
    xml_writer_settings<char> w('\t', 1); 
    read_xml(filename, pt, boost::property_tree::xml_parser::trim_whitespace); 

    ptree &resultSetNode = pt.get_child("root.result_set"); 
    ptree resultNode; 
    resultNode.put("tolerance", 100); 
    resultSetNode.add_child("result", resultNode); 

    write_xml(filename, pt, std::locale(), w); 

} 

int main() 
{ 
    initialise("sample.xml"); 

    for(int i = 0; i < 2; ++i) 
    { 
    save1("sample.xml"); 
    } 
    std::cout << "Success!!!\n"; 
    return 0; 
} 

回答

0

這是我升壓郵件列表上回答的複製/粘貼:

我覺得你在這裏誤解了整個事情。

你有很多節點,其XPath是根/ result_set的,但所有的 他們具有標識它們的屬性:當你打電話get_child你正在(從升壓 文檔)的任意節點result_number

self_type & get_child(const path_type & path) ; 
    Get the child at the given path, or throw ptree_bad_path. 

    Notes: 
    Depending on the path, the result at each level may not be 
    completely determinate, i.e. if the same key appears 
    multiple times, which child is chosen is not specified. 
    This can lead to the path not being resolved even though 
    there is a  descendant with this path. Example: 
    a -> b -> c 
     -> b 
The path "a.b.c" will succeed if the resolution of "b" chooses the 

第一個這樣的節點,但如果它選擇第二個節點則失敗。

我猜你應該使用對根的迭代器找到最後執行的設定 ,然後得到該節點的引用,然後將結果添加到它:

from begin() to end(), find the max result_number or 
    just the one that matches count() 

鏈接,以提高DOC:http://www.boost.org/doc/libs/1_41_0/doc/html/boost/property_tree/basic_ptree.html#id973373-bb