如何返回最后一次提升ptree项

时间:2016-09-07 11:00:35

标签: c++ boost boost-propertytree

我想创建一个函数来查找boost :: property_tree :: ptree中的最后一项并将其作为ptree返回

我有以下代码找到最后一项,但我不知道如何将其ptree作为返回值传递 - 它应该是可能的,但是我没有找到任何返回ptree但没有先复制它的示例。

想要这样做的原因是能够使用新值处理最后一项的更新

BOOST_FOREACH( boost::property_tree::ptree::value_type const&rowPair, pt.get_child( "" ) ) 
{
    cout << rowPair.first << ": " << endl;

    BOOST_REVERSE_FOREACH( boost::property_tree::ptree::value_type const& itemPair, rowPair.second ) 
    {
            std::cout << "\t" << itemPair.first << " ";

            BOOST_FOREACH( boost::property_tree::ptree::value_type const& node, itemPair.second ) 
            {
                    std::cout << node.second.get_value<std::string>() << " ";
            }

            std::cout << std::endl;
            //TODO: return itemPair
            break;  
    }


    std::cout << std::endl;
}

试图澄清一点。 以下代码行附加到已存在的条目

pt.insert(pt.get_child("item").end(), subpt.front());

如果Items.item只有一个项目,那么这种方法很有效,但是如果它有多个&#34;项目&#34;和多个&#34; item&#34;在Items中,它将在第一个Items.item中插入新条目

<xml>
<listOfItems>
<Items>
  <item>
  </item>
  <item> 
  ... inserts new sub pt here
  </item>
</Items>
<Items>
  <item>
  </item>
  <item> 
  ... Should insert new sub pt here
  </item>
</Items>
</listOfItems>

所以为了得到我想要的东西,我必须以某种方式使插入语句更好或创建一个函数,它可以给我正确的项目,然后插入其中

1 个答案:

答案 0 :(得分:0)

找到了解决方案:

<?xml version="1.0" encoding="utf-8"?>
<listOfItems>
<Items>
  <Item> </Item>
  <Item> </Item>
  <Item> </Item>
  <Item> </Item>
</Items>
<Items>
  <Item> </Item>
  <Item> </Item>
  <Item> </Item>
  <Item> </Item>
   insert here...
</Items>
</listOfItems>

...

boost::property_tree::ptree::value_type findLastItem(boost::property_tree::ptree pt)
{
  ptree _empty_tree;
  BOOST_REVERSE_FOREACH(ptree::value_type &v2, pt.get_child("listOfItems", _empty_tree))
  {
   if(v2.first == "Items")
   { 
       BOOST_REVERSE_FOREACH(ptree::value_type &v3, v2.second)
       {
           if(v3.first == "Item"){
              cout << "- OK: Found Last Item " << endl;
              return v3; // then use add_child on this to append a new item 
           }
       }
   }
  }
}
相关问题