Boost PropertyTree:检查child是否存在

Boost PropertyTree: check if child exists

本文关键字:是否 存在 child 检查 PropertyTree Boost      更新时间:2023-10-16

我试图编写一个XML解析器,将XML文件解析为boost::property_tree,并遇到了这个问题。如何(快速)检查某个属性的子元素是否存在?

显然,我可以迭代所有的孩子使用BOOST_FOREACH -然而,是不是有一个更好的解决方案?

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

这里有几个其他的选择:

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>

移除const:

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

另一种可以使用的方法是在您不想检查一些可能丢失的子/节点时使用。尝试使用迭代器:

if (node.begin() != node.end()) { // Node does have child[ren]
     // Code to process child nodes
}

您可以使用count()检查标签是否存在

typedef boost::property_tree pt;
pt::ptree tree;
pt::read_xml(filename, tree);
int bodyCount = tree.count( "body" );
if( bodyCount == 0 )
{
  cout<<"Failed : body tag not found"<<endl;
  return -1;
}