使用boostproperty_tree解析xml文件,并将所选内容放入std::映射中

Parsing xml file with boost property_tree and put selected content to a std::map

本文关键字:std 映射 tree boostproperty 解析 xml 文件 使用      更新时间:2023-10-16

从一个java属性XML文件中,我想找到每个名为entry的元素(在根元素properties内)。然后将其属性key的内容放在std::map<std::string, std::string>中作为关键字,将元素的内容(在<entry></entry>之间)作为值。到目前为止,我使用的是boostproperty_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>

我会让它更简单:

在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库。

除此之外,我认为没有什么错。