2016-02-19 82 views
1

我跟着這個鏈接http://www.technical-recipes.com/2014/using-boostproperty_tree/解析xml。但是,如何在不指定特定鍵的情況下讀取整個xml?我想下面的代碼,但它無法處理它,我得到的錯誤爲No such node.閱讀xml使用增強

代碼:

const std::string XML_PATH1 = "./test1.xml"; 
#define ROOTTAG "roottag" 
boost::property_tree::ptree pt1; 
boost::property_tree::read_xml(XML_PATH1, pt1); 
BOOST_FOREACH(boost::property_tree::ptree::value_type & node, pt1.get_child(ROOTTAG)) 
{ 
    std::string tagname = node.first; 
    tagname += "."; 
    boost::property_tree::ptree subtree = node.second; 
    BOOST_FOREACH(boost::property_tree::ptree::value_type & v, subtree.get_child(node.first.data())) 
    { 
     //does not enter here 
     tagname += v.first.data(); 
     tagname += "."; 
     xmlmap[tagname] = tagvalue; 
    } 
} 

什麼已經在第二循環,而不是node.first.data()指定?

BOOST_FOREACH(boost::property_tree::ptree::value_type & v, subtree.get_child(node.first.data())) 

請注意,我必須使用BOOST_FOREACH本身,並使用相同的方法。 我引用了很多網站,但無法找到如何在不指定特定密鑰的情況下讀取整個xml。

另外,如何使用上述方法讀取多層次的XML?

+3

你一直在問相同的[自二月十日](http://stackoverflow.com/questions/35314178/c-how-to-read-xml-using-boost-xml-parser-and -store-在圖)。我們得到什麼緩解?你能/只是/展示預期的輸入和輸出? – sehe

回答

1

當然,整個「我想壓扁成圖這個」看起來是一個徒勞無益的,因爲我在我的答案認爲這裏:

然而,由於你似乎意圖,只是不能拿出代碼遞歸遍歷一個ptree中,這裏是一個開始:

Live On Coliru

void flatten(boost::property_tree::ptree const& pt, Flat& xmlmap, std::string const& prefix = "") { 
    using namespace boost::property_tree; 

    bool has_child_elements = false; 
    BOOST_FOREACH (ptree::value_type const& child, pt) { 
     has_child_elements |= (child.first != "<xmlattr>"); 
     flatten(child.second, xmlmap, prefix + "." + child.first); 
    } 

    if (!has_child_elements) { 
     std::string val = pt.get_value(""); 
     if (!val.empty()) 
      xmlmap[prefix] = val; 
    } 
} 

當調用此像這樣:

int main() { 
    boost::property_tree::ptree pt; 
    boost::property_tree::read_xml("test.xml", pt); 

    Flat m; 
    flatten(pt.get_child("roottag"), m, "DEMO"); 

    BOOST_FOREACH(Flat::value_type const& p, m) { 
     std::cout << p.first << "\t= '" << p.second << "'\n"; 
    } 
} 

它打印如

DEMO.billTo.<xmlattr>.country = 'US' 
DEMO.billTo.city = 'Old Town' 
DEMO.billTo.name = 'Robert Smith' 
DEMO.billTo.state = 'PA' 
DEMO.billTo.street = '8 Oak Avenue' 
DEMO.billTo.zip = '95819' 
DEMO.comment = 'Hurry, my lawn is going wild!' 
DEMO.items.item.<xmlattr>.partNum = '926-AA' 
DEMO.items.item.USPrice = '39.98' 
DEMO.items.item.comment = 'Confirm this is electric' 
DEMO.items.item.productName = 'Baby Monitor' 
DEMO.items.item.quantity = '1' 
DEMO.items.item.shipDate = '1999-05-21' 
DEMO.shipTo.<xmlattr>.country = 'US' 
DEMO.shipTo.city = 'Mill Valley' 
DEMO.shipTo.name = 'Alice Smith' 
DEMO.shipTo.state = 'CA' 
DEMO.shipTo.street = '123 Maple Street' 
DEMO.shipTo.zip = '90952' 
+0

示例[Live On Coliru](http://coliru.stacked-crooked.com/a/491531c7f187e00e) – sehe

+0

如何處理其具有多個具有相同名稱的子項的情況,該值將被覆蓋在地圖 – Namitha

+0

或如何存儲子項與地圖中的逗號分隔值相同的名稱? – Namitha