c++ - boost 属性树 : Remove attribute from a node

标签 c++ c++11 boost boost-propertytree

我有以下 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<gexf>
  <graph>
    <nodes>
      <node id="0" label="0" start="0" end="25"/>
      <node id="1" label="1" start="1"/>
      <node id="2" label="2" start="2"/>
      ...
    </nodes>
    <edges>
      <edge id="0" source="0" target="1" start="7" end="19"/>
      <edge id="1" source="0" target="2" start="8" end="20"/>
      ...
    </edges>
  </graph>
</gexf>

我想从带有 source="0"target="1 的边缘删除 startend 属性".

我尝试这样做的方式是在下面的代码中。假设 XML 文件名为 ptree_test.gexf,我将其读入,在树中找到正确的边,然后尝试使用 erase 删除属性。

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <iostream>

using boost::property_tree::ptree;

int main(int argc, char *argv[]) {

  ptree pt;

  read_xml("ptree_test.gexf", pt);

  // Now find edge (0, 1) and delete the start and end attributes
  ptree edge;
  int id1, id2;
  id1 = 0;
  id2 = 1;

  for(auto &e : pt.get_child("gexf.graph.edges")) {
    int s, t;
    s = e.second.get<int>("<xmlattr>.source");
    t = e.second.get<int>("<xmlattr>.target");

    // Check if this is the correct edge
    // Two checks because it can be reversed
    if((id1 == s && id2 == t) || (id1 == t && id2 == s)) {
      edge = e.second;
      break;
    }
  }

  for(auto & attr : edge.get_child("<xmlattr>")) {
    if(attr.first == "end" || attr.first == "start") {
      edge.erase(attr.first);
    }
  }

  write_xml(std::cout, pt);
  return 0;
}

这是行不通的。它不会删除该属性。事实上,如果我输入一个调试语句来打印 edge.erase(attr.first) 的返回值,它会显示 0

最佳答案

在回答之前,我想再次劝阻您不要将 Boost.PropertyTree 用作快速而肮脏的 XML 处理系统。请use a real XML parser ;有很多可供选择,有些非常有效并且需要很少的依赖维护。

无论如何,你的问题来自your use of erase .您正在尝试从您正在迭代 的列表中删除一个元素。那是行不通的。并非没有针对循环的特殊编码。

所以你不能在这里使用基于范围的 for 循环。您必须在迭代器上使用真正的 for 循环。

auto &children = edge.get_child();
for(auto &attrIt = children.begin(); attrIt != children.end();)
{
  auto &attr = *attrIt;
  //Do stuff here.


  if(attr.first == "end" || attr.first == "start")
    attrIt = children.erase(attrIt);
  else
    ++attrIt;
}

关于c++ - boost 属性树 : Remove attribute from a node,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14780665/

相关文章:

c++ - 我对 n3797 8.5.3/5 的解释是否正确?

c++ - 如何解锁 boost::upgrade_to_unique_lock(由 boost::shared_mutex 制成)?

c++ - DEFLATED 数据将始终大于未压缩的输入数据

C++ 为什么返回的 const 引用可以被修改?

c++ - constexpr 唯一标识,使用 clang 编译但不使用 gcc

c++ - 通过不明确的转换运算符进行引用绑定(bind)

boost - 在哪里可以找到 bcp for boost?

c++ - 程序中止挂起命名的互斥量

c++ - 霸气C++游戏

c++ - auto_ptr 或 shared_ptr