Boost.PropertyTree子路径处理

时间:2015-03-22 19:27:51

标签: c++ boost boost-propertytree

以下是我想用Boost.PropertyTree库处理的实际xml的简化示例。实际上,原始xml文件中还有很多其他字段

<?xml version="1.0" encoding="UTF-8"?> 
<foo>
   <bar>
     <item>
       <link>http://www.one.com</link>
     </item>
     <item>
       <link>http://www.two.net</link>
     </item>
     <item>
       <link>http://www.sex.gov</link>
     </item>
     ...
   </bar>
 </foo>

我需要遍历所有link标记。有一个必需代码的例子。

for (auto item: pt.get_child("foo.bar"))
  if ("item" == item.first)
    for (auto prop: item.second)
      if ("link" == prop.first)
        std::cout << prop.second.get_value<std::string>() << std::endl;

这对于简单的目的来说太难看了。 有没有办法简化它?例如,我可以等待下一个代码有效用于此目的:

for (auto item: pt.get_child("foo.bar.item.link"))
  std::cout << item.second.get_value<std::string>() << std::endl;

此代码不起作用,但它说明了我想要获得的内容。

1 个答案:

答案 0 :(得分:1)

这种功能并不存在。

坦率地说,如果你想要XPath,只需使用支持它的库:

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

int main() {
    pugi::xml_document doc;
    doc.load(std::cin);

    for (auto item: doc.select_nodes("//foo/bar/item/link/text()"))
        std::cout << "Found: '" << item.node().value() << "'\n";
}

否则,您可以自己做出努力:

template <typename Tree, typename Out, typename T = std::string>
Out enumerate_path(Tree const& pt, typename Tree::path_type path, Out out) {
    if (path.empty())
        return out;

    if (path.single()) {
        *out++ = pt.template get<T>(path);
    } else {
        auto head = path.reduce();
        for (auto& child : pt)
            if (child.first == head)
                out = enumerate_path(child.second, path, out);
    }

    return out;
}

现在你可以把它写成例如:

<强> Live On Coliru

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

template <typename Tree, typename Out, typename T = std::string>
Out enumerate_path(Tree const& pt, typename Tree::path_type path, Out out) {
    if (path.empty())
        return out;

    if (path.single()) {
        *out++ = pt.template get<T>(path);
    } else {
        auto head = path.reduce();
        for (auto& child : pt)
            if (child.first == head)
                out = enumerate_path(child.second, path, out);
    }

    return out;
}

int main() {
    using namespace boost::property_tree;

    ptree pt;
    read_xml("input.txt", pt);

    enumerate_path(pt, "foo.bar.item.link",
            std::ostream_iterator<std::string>(std::cout, "\n"));
}

打印

http://www.one.com
http://www.two.net
http://www.sex.gov
相关问题