我正在尝试使用 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
标签已正确打开和关闭,因此尽管有属性,它也应该能够找到它,对吧?
希望有人知道这里发生了什么!
最佳答案
你在做其他错误/不同的事情:
#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/