-->

Boost.PropertyTree子路径处理(Boost.PropertyTree subpath

2019-10-22 07:49发布

下面是实际的XML的降低了的采样我想与处理Boost.PropertyTree库。 其实,有一个原始的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;

此代码不能正常工作,但它说明,我想获得。

Answer 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;
}

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

住在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


文章来源: Boost.PropertyTree subpath processing