Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top