使用boostproperty_tree解析xml文件,并将所选内容放入std::映射中
Parsing xml file with boost property_tree and put selected content to a std::map
从一个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库。
除此之外,我认为没有什么错。
相关文章:
- C++匿名结构作为std::映射值
- 如何从存储在std::映射中的std::集中删除元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 将唯一指针插入std::映射
- 重载std::映射不同的密钥类型
- std::映射,只有move构造函数可用
- std::映射服装比较函数和函数/lambda错误
- std::映射导致插入时出现C2664错误
- 将从std::映射中获取的std::pair引用传递给接受std::对引用的函数
- std::映射键作为模板化结构与枚举成员
- std ::映射以构造为钥匙
- 在锁定下清除STD ::映射,而移动到临时对象
- 计算向量的std ::映射为键的值,并将双倍作为值
- 写入/读取 std::映射到二进制文件需要运算符
- 我如何正确地为std ::映射分配内存
- 如何打印包含整数和整数集的std::映射
- 在字符串的std::映射中找到编译错误,long
- 将std ::映射复制到std ::对向量
- 使用std ::映射的键的部分匹配
- 遍历std ::映射,效果少于迭代器之间的比较