Boost PropertyTree: check if child exists

僤鯓⒐⒋嵵緔 提交于 2020-05-09 19:26:27

问题


I'm trying to write an XML parser, parsing the XML file to a boost::property_tree and came upon this problem. How can I check (quickly) if a child of a certain property exists?

Obviously I could iterate over all children using BOOST_FOREACH - however, isn't there a better solution to this?


回答1:


optional< const ptree& > child = node.get_child_optional( "possibly_missing_node" );
if( !child )
{
  // child node is missing
}



回答2:


Here's a couple of other alternatives:

if( node.count("possibliy_missing") == 0 )
{
   ...
}

ptree::const_assoc_iterator it = ptree.find("possibly_missing");
if( it == ptree.not_found() )
{
   ...
}



回答3:


Include this:

#include <boost/optional/optional.hpp>

Remove the const:

boost::optional< ptree& > child = node.get_child_optional( "possibly_missing_node" );
if( !child )
{
  // child node is missing
}



回答4:


While these solutions might appear to avoid iterating over the tree, just keep in mind that under the covers they are still doing exactly that, so you are making your algorithm potentially n^2... if you are concerned about performance and have memory to spare, you could use a map container for quick lookups.



来源:https://stackoverflow.com/questions/7568607/boost-propertytree-check-if-child-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!