c++ - boost 属性树 : How to delete the specified parameters of the node

标签 c++ boost boost-propertytree

<root>
    <stu id="1">
        <name>a</name>
    </stu>
    <stu id="2">
        <name>b</name>
    </stu>
    <stu id="3">
        <name>c</name>
    </stu>
</root>

我想删除 id = 2 节点。 我用

boost::property_tree::ptree pt;
pt.erase(Node);

但这会删除所有节点

最佳答案

假设您在删除属性时没有遇到问题,下面是使用 Boost Property Tree 的战斗解决方案:

Live On Coliru

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

using boost::property_tree::ptree;
static auto const pretty = boost::property_tree::xml_writer_make_settings<std::string>(' ', 4);

template <typename Tree>
auto find_children(Tree& pt, std::string const& key) {
    std::vector<typename Tree::iterator> matches;

    for (auto it = pt.begin(); it != pt.end(); ++it)
        if (it->first == key)
            matches.push_back(it);

    return matches;
}

int main() {
    ptree pt;
    {
        std::istringstream iss(R"(<root><stu id="1"><name>a</name></stu><stu id="2"><name>b</name></stu><stu id="3"><name>c</name></stu></root>)");
        read_xml(iss, pt);
    }

    auto& root = pt.get_child("root");

    for (auto stu : find_children(root, "stu")) {
        if (2 == stu->second.get("<xmlattr>.id", -1)) {
            std::cout << "Debug: erasing studen " << stu->second.get("name", "N.N.") << "\n";
            root.erase(stu);
        }
    }

    write_xml(std::cout, pt, pretty);
}

打印:

Debug: erasing student b
<?xml version="1.0" encoding="utf-8"?>
<root>
    <stu id="1">
        <name>a</name>
    </stu>
    <stu id="3">
        <name>c</name>
    </stu>
</root>

使用 XML 库

当然,使用 XML 库要容易得多:

#include <iostream>
#include <pugixml.hpp>

int main() {
    pugi::xml_document doc;
    doc.load_string(R"(<root><stu id="1"><name>a</name></stu><stu id="2"><name>b</name></stu><stu id="3"><name>c</name></stu></root>)");

    for (auto& n : doc.select_nodes("//root/stu[@id=2]")) {
        auto node = n.node();
        node.parent().remove_child(node);
    }

    pugi::xml_writer_stream w(std::cout);
    doc.save(w);
}

关于c++ - boost 属性树 : How to delete the specified parameters of the node,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46420789/

相关文章:

c++ - 如何使用 boost::property_tree 解析带根数组的 JSON

c++ - C++中图的BFS和DFS

c++ - 您可以将附加参数传递给谓词吗?

c++ - 跨平台浏览器检测

c++ - Boost Log 更改默认 logging::core 格式化程序?

c++ - 中断 boost 线程

algorithm - 如何使用 boost 将复杂的多边形划分为简单的多边形?

c++ - 将 boost 属性树(ptree)序列化为 vector 的最快方法是什么

c++ - 从字符串 vector 分配字符串

c++11 - 在Boost Property树库中,如何以自定义方式处理文件未找到错误(C++)