boost property_tree: 遍历重复子元素中重复子元素的属性

boost property_tree: iterating through attributes of repeated child elements within repeated child elements

我有以下 XML 文档:

<root>
  <scenario name="ScenarioA">
    <param name="ParamA">1</param>
    <param name="ParamB">2</param>
    <param name="ParamC">3</param>
  </scenario>
  <scenario name="ScenarioB">
    <param name="ParamA">1</param>
    <param name="ParamB">2</param>
    <param name="ParamC">3</param>
  </scenario>
  <scenario name="ScenarioC">
    <param name="ParamA">1</param>
    <param name="ParamB">2</param>
    <param name="ParamC">3</param>
  </scenario>
</root>

使用 boost::property_tree::ptree,我可以执行以下操作来遍历顶级元素:

ptree scenarioTree = myTree.get_child("root");
for (const auto& itr : scenarioTree) {
    if (itr.second.get<std::string>(<xmlattr>.name) == "ScenarioA") {
        // additional logic
    }
}

我无法在每个场景下检索 "param" 标签的任何属性,在 itr.second 上使用相同的方法:

ptree scenarioTree = myTree.get_child("root");
for (const auto& itr : scenarioTree) {
    if (itr.second.get<std::string>(<xmlattr>.name) == "ScenarioA") {
        ptree paramTree = itr.second;
        // Iterate through "param" tags
        for (const auto& paramItr: paramTree) {
            if (paramItr.second.get<std::string>(<xmlattr>.name) == "ParamA") {
                // doesn't exist
            }
        }
    }
}

我做错了什么?我的理论是这是 ptree 迭代器 returns (self) 与标准 ptree 之间的转换问题,但我不确定如何检索内部子属性。我能够检索参数标签名称(通过 first)和参数值(通过 second.data()),只是没有属性。

属性 树中的属性添加为 sub-nodes。 下面节点可以翻译

  <scenario name="ScenarioA">
    <param name="ParamA">1</param>
    <param name="ParamB">2</param>
    <param name="ParamC">3</param>
  </scenario>

变成这样的东西:

  scenario 
     xmlattr.name   ScenarioA // this node doesn't have subnode with attribute name
     param 
       xmlattr.name  -> ParamA
     param 
       xmlattr.name  -> ParamB
     param 
       xmlattr.name  -> ParamC

当您找到以 ScenarioA 作为属性的场景时,您正在迭代其 children。这个节点有4children。对于每个 child 您想查找 name 属性,但其中一个没有此属性。找不到路径时,方法 get 抛出异常。您可以捕获此异常或使用 default-value:

boost::property_tree::ptree scenarioTree = pt.get_child("root");
for (const auto& itr : scenarioTree) 
{
    if (itr.second.get<std::string>("<xmlattr>.name") == "ScenarioA") 
    {
        boost::property_tree::ptree paramTree = itr.second;
        for (const auto& paramItr: paramTree) 
        {
            if (paramItr.second.get<std::string>("<xmlattr>.name","") == "ParamA") 
            {                                                    ^^^^ default value
                cout << "ParamA was found in ScenarioA" << endl;
            }
        }
    }
}

结果我得到 ParamA was found in ScenarioA