c++ - 使用 boost property_tree 解析 xml 文件并将选定的内容放入 std::map

标签 c++ xml boost boost-propertytree

我想从 java 属性 XML 文件中找到名为 entry 的每个元素(在根元素内 properties )。然后把它属性的内容keystd::map<std::string, std::string>作为键,元素的内容(在 <entry></entry> 之间)作为值。 到目前为止,我正在使用 boost property_tree。 但由于我不熟悉解析 XML 文档,所以我想知道是否有任何我在这里没有看到的陷阱,或者是否有比这更简单的方法。

std::map<std::string, std::string> mMap;
BOOST_FOREACH(boost::property_tree::ptree::value_type &v, pt.get_child("properties"))
{
    if (v.first == "entry")
    {
        std::string sVal = v.second.get_child("<xmlattr>.key").data();

        if (sVal.compare("Foo") == 0)
            mMap[sVal] = v.second.data();
        else if (sVal.compare("Bar") == 0)
            mMap[sVal] = v.second.data();
        else if(...)
    }
}

XML:

<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="Foo">This is a sentence.</entry>
    <entry key="Bar">And another one.</entry>
    <entry key=...
</properties>

最佳答案

我会让它更简单:

Live On Coliru

Map read_properties(std::string const& fname) {
    boost::property_tree::ptree pt;
    read_xml(fname, pt);

    Map map;

    for (auto& p : pt.get_child("properties")) {
        auto key = p.second.get<std::string>("<xmlattr>.key");
        if (!map.insert({ key, p.second.data() }).second)
            throw std::runtime_error("Duplicate key: " + key);
    }

    return map;
}

如果您渴望更多验证或“XPath”感觉,我建议您使用 XML 库。

除此之外,我看不出有什么不妥。

关于c++ - 使用 boost property_tree 解析 xml 文件并将选定的内容放入 std::map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34650476/

相关文章:

c++ - 只产生一个值的迭代器?

java - jaxb 是否有可能在基于 xsd 的验证过程中显示更多错误

Android:浏览量超过80; Viewflipper 或 Fragments(或其他东西..)

外部服务器的 C++ 客户端和外部客户端的服务器与 boost::asio 协程同时使用

c++ - 用于将一系列数字从一行识别为 vector 的 Boost Spirit 语法?

C++查找子字符串中字符串的最后一次出现

c++ - 在 C++ 中使用回调会增加耦合吗?

c++ - 修复 trie c++ 中的段错误

c++ - 将指定数量的零填充到 char 数组

c# - 如何最好地从方法中测试 XML 的有效性?