【问题标题】:Check if an element does exists in xml file with boost property tree使用boost属性树检查xml文件中是否存在元素
【发布时间】:2018-03-14 14:06:54
【问题描述】:

我正在使用以下类型的 boost 属性树解析 XML 文件:

<DocName>
    <InitCommands>
        <OptionalCommands>
            <command name="write" address="0x00000000"/>
            <command name="write" address="0x00000000"/>
            <command name="write" address="0x00000000"/>
        </OptionalCommands>
        <command name="write" address="0x00000000"/>
        <command name="write" address="0x00000000"/>        
    </InitCommands>
</DocName>

我想检查某个元素是否存在于 XML 树中。以下是我正在使用的代码:

namespace pt = boost::property_tree;
int main (){
   pt::ptree prop_tree;
   read_xml ("my.xml", prop_tree);
   pt::ptree::const_assoc_iterator it;
   it  = prop_tree.find("DocName.InitCommands.OptionalCommands");
   if (it != prop_tree.not_found())
     std::cout <<"Optional Options found !" << std::endl;              
}

但是,运行此代码会返回

it == prop_tree.not_found()

如果我尝试找到我的 xml 文件的根元素,这会起作用,即

it  = prop_tree.find("DocName");

有人可以建议如何使用这个 find() 函数吗?

【问题讨论】:

    标签: c++ xml boost-propertytree


    【解决方案1】:

    find()的文档

    assoc_iterator find(const key_type & key);
    34. 用给定的键找到一个孩子,如果没有,则用 not_found()。如果多个具有相同的键,则无法保证返回哪个孩子。

    get_child()

    self_type & get_child(const path_type & path);
    45. 在给定的路径上获取孩子,或者抛出 ptree_bad_path。

    我猜,find 正在寻找直系子元素——这可以解释为什么寻找根元素有效——而get_child 旨在沿着整个路径前进。


    所以,要么一步一步走,例如像

    it = prop_tree.find("DocName");
    it = it->find("InitCommands");
    it = it->find("OptionalCommands");
    

    或创建一个path_type 并改用get_child

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-11
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 2020-06-09
      相关资源
      最近更新 更多