2017-02-24 17 views
2

我試圖將一個boost :: property_tree :: ptree的元素傳遞給一個函數。 詳細地說,我必須從中ptree中被初始化下面的XML代碼:boost :: property_tree傳遞子樹,包括<xmlattr>

<Master Name='gamma'> 
    <Par1 Name='name1'> 
     <Value>0.</Value> 
     <Fix>1</Fix> 
    </Par1> 
    <Par2 Name='name2'> 
     <Value>0.</Value> 
     <Fix>1</Fix> 
    </Par2> 
</Master> 

我想通過它的一部分到一個函數。基本上,我想通過:

<Par2 Name='name2'> 
     <Value>0.</Value> 
     <Fix>1</Fix> 
    </Par2> 

功能看起來是這樣的:

void processTree(which_type_do_I_put_here element){ 
    std::string n = element.get<std::string>("<xmlattr>.Name"); 
    double val = element.get<double>("Value"); 
} 

總的來說,我可以通過使用ptree::get_child("par2")子樹。這具有缺點,即該功能無法訪問此節點的<xmlattr>

如何通過<xmlattr>訪問該樹的這部分? 提前感謝您的任何想法。

〜彼得

+0

''沒什麼特別的,它只是一個子樹。所以'get_child(「par2」)'只返回一棵具有''子樹的樹。 – zett42

回答

3

類型爲ptree

通常我可以使用ptree :: get_child(「par2」)傳遞一個子樹。

確實。

這具有該功能必須在此節點

的無訪問權限的缺點是不正確的:它打印

Live On Coliru

#include <boost/property_tree/xml_parser.hpp> 
#include <iostream> 

std::string const sample = R"(
<Master Name='gamma'> 
    <Par1 Name='name1'> 
     <Value>0.</Value> 
     <Fix>1</Fix> 
    </Par1> 
    <Par2 Name='name2'> 
     <Value>0.</Value> 
     <Fix>1</Fix> 
    </Par2> 
</Master> 
)"; 

using boost::property_tree::ptree; 

void processTree(ptree const& element) { 
    std::string n = element.get<std::string>("<xmlattr>.Name"); 

    double val = element.get<double>("Value"); 
    std::cout << __FUNCTION__ << ": n=" << n << " val=" << val << "\n"; 
} 

int main() { 
    ptree pt; 
    { 
     std::istringstream iss(sample); 
     read_xml(iss, pt); 
    } 

    processTree(pt.get_child("Master.Par2")); 
} 

processTree: n=name2 val=0 
+0

工程就像一個魅力。我之前試圖實現這一點,並出於某些原因,我不記得它沒有工作。非常感謝! – hansgans