如何从ptree异常中获取xml行号

yon*_*igo 8 c++ xml boost exception ptree

我正在使用boost ptree来读取这样的xml文件:

ptree myTree;
... /*open xml file*/
try{
    myTree.get<string>(s);
}
catch(boost::exception const&  ex)
{
/*get useful info!*/
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用该what()函数,但它会产生错误和我刚刚发送的字符串.

有没有办法获得更多有用的信息,如xml中与呼叫相关的行号?

Joh*_*nck 2

如果您想检测格式错误的 XML(与 XML 文档相反,XML 文档根本不包含您期望的值,在这种情况下无法获取行号):

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

int main(int argc, char* argv[])
{
  boost::property_tree::ptree pt;
  try {
    read_xml(argv[1], pt);
  } catch (const boost::property_tree::xml_parser::xml_parser_error& ex) {
    std::cerr << "error in file " << ex.filename() << " line " << ex.line() << std::endl;
  }
}
Run Code Online (Sandbox Code Playgroud)

现在假设这t.xml不是一个有效的 XML 文档:

$ a.out t.xml
error in file t.xml at line 10
Run Code Online (Sandbox Code Playgroud)