I am using boost ptree to read an xml file like this:
ptree myTree;
... /*open xml file*/
try{
myTree.get<string>(s);
}
catch(boost::exception const& ex)
{
/*get useful info!*/
}
I know I can use the what()
function, but it produces an error and the strings I just sent.
Is there a way to get more useful information like the line numbers in the xml that are relevant to the call?
If you want to detect malformed XML (as opposed to XML documents which simply don't contain the values you expect, in which case line numbers aren't feasible to obtain):
#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;
}
}
Now given that t.xml
is not a valid XML document:
$ a.out t.xml
error in file t.xml at line 10
A boost::property_tree has no concept of line numbers anymore. Basically it is just an iterable tree. It doesn't know if its contents where parsed from a file, added programmatically or came out of nowhere. Therefore there is just no way to get a line number when the tree doesn't contain the values you are looking for.
Things you might want to consider:
get<string>
. There are many variant allowing you to specify default values, getting null, or do something else, if the data you are expecting does not exist.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With