Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get xml line number from ptree exception

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?

like image 204
yonigo Avatar asked Jul 22 '13 05:07

yonigo


2 Answers

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
like image 157
John Zwinck Avatar answered Nov 08 '22 15:11

John Zwinck


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:

  • Improve your XML schema to catch missing information on parse time. As @JohnZwinck already pointed out line numbers still exist while parsing. You should definitely be able to rule out "that the person creating the xml decided to change [anything structurally]" like this.
    You make it sound like they are in charge of deciding how the XML must look like. Even if this is the case your program still expects the XML to be formed in a certain way to do meaningful things with it. And this is where your schema comes into play. Now if they decide to change their schema you will instantly notice where there is a mismatch to the schema you designed for.
  • Use another variant of 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.
    Your try-instant-catch-debug-continue code pattern suggests that you aren't entirely sure what data to expect and that it is noncritical if the data isn't there. Exceptions are for exceptional situations. It seemsmto me that this isn't one.
like image 20
Jonas Bötel Avatar answered Nov 08 '22 16:11

Jonas Bötel