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?

有帮助吗?

解决方案

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

其他提示

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() )
{
   ...
}

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
}

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top