c++ - Boost property tree xml解析No such node()

标签 c++ xml boost boost-propertytree

我正在尝试使用 boost/propert_tree 库解析 XML 文件。我可以正确获取 xml 文件和所有内容,但是当我寻找 child 时,它找不到任何东西。

我有一个 input.xml 文件:

<ax:hello someatribute:ax="dwadawfesfjsefs">
    <something>523523</something>
    <ax:whatever>
        <ax:service_tree>
            <ax:service>some</ax:service>
            <ax:url>someulr</ax:url>
        </ax:service_tree>
    </ax:whatever>
</ax:hello>

我尝试解析 xml 的函数:

void parseXml(std::istream &stream)
{
    using boost::property_tree::ptree;
    ptree pt;
    read_xml(stream, pt);
    BOOST_FOREACH(ptree::value_type const &value, pt.get_child("ax:hello"))
    {
        std::cout << value.first;
    }
}

主要功能:

int main()
{
    std::ifstream stream("input.xml");
    parseXml(stream);
    return 0;
}

我得到的错误信息是:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl >' what(): No such node (ax:hello) Aborted (core dumped)`

如您所见,ax:hello 标签已正确打开和关闭,因此尽管有属性,它也应该能够找到它,对吧?

希望有人知道这里发生了什么!

最佳答案

你在做其他错误/不同的事情:

Live On Coliru

#include <iostream>
#include <fstream>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>

void parseXml(std::istream &stream)
{
    using boost::property_tree::ptree;
    ptree pt;
    read_xml(stream, pt);
    BOOST_FOREACH(ptree::value_type const &value, pt.get_child("ax:hello"))
    {
        std::cout << value.first << "\n";
    }
}

int main()
{
    std::istringstream stream(R"(
        <ax:hello someatribute:ax="dwadawfesfjsefs">
            <something>523523</something>
            <ax:whatever>
                <ax:service_tree>
                    <ax:service>some</ax:service>
                    <ax:url>someulr</ax:url>
                </ax:service_tree>
            </ax:whatever>
        </ax:hello>
)");
    parseXml(stream);
}

打印

<xmlattr>
something
ax:whatever

更复杂的转储:

void dump(ptree const& pt, std::string const& indent = "") {
    for (auto& node : pt) {
        std::cout << indent << node.first;
        auto value = boost::trim_copy(node.second.get_value(""));
        if (!value.empty())
            std::cout << ": '" << value << "'";
        std::cout << "\n";
        dump(node.second, indent + "    ");
    }
}

打印 Live On Coliru也是

ax:hello
    <xmlattr>
        someatribute:ax: 'dwadawfesfjsefs'
    something: '523523'
    ax:whatever
        ax:service_tree
            ax:service: 'some'
            ax:url: 'someulr'

关于c++ - Boost property tree xml解析No such node(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38541594/

相关文章:

c++ - 关于cin函数到一个对象的所有public成员

c# - 用c#写这个xml

hadoop 中的 XML 处理

c++ - 如何返回 boost multi_index 迭代器的开始和结束

c++ - 用更快的方法替换这些方法

c++ - 通过注入(inject)进行死锁检测

c++ - 是语句value += i;与 value = value + i 完全相同?

c++ - RVO(返回值优化)是否适用于所有对象?

C# 解析 XML 文件

c++ - 我如何最好地阅读 boost 序列化文件?