gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:10:20 25 4
gpt4 key购买 nike

我有以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com