我想从 java 属性 XML 文件中找到名为 entry
的每个元素(在根元素内 properties
)。然后把它属性的内容key
在std::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>
最佳答案
我会让它更简单:
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/