How can I get xml line number from ptree exception

I use boost ptree to read an XML file as follows:

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

I know that I can use the what() function, but it causes an error and the lines I just sent.

Is there a way to get more useful information, such as line numbers in xml, that are relevant to the call?

+8
c ++ boost xml exception ptree
source share
2 answers

If you want to detect invalid XML (unlike XML documents that simply do not contain the expected values, in this case the line numbers are not amenable):

 #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 not a valid XML document:

 $ a.out t.xml error in file t.xml at line 10 
+2
source share

Boost :: property_tree no longer has the concept of line numbers. In fact, it is just an iterable tree. He does not know whether its contents were parsed from a file, added programmatically or out of nowhere. Therefore, there is no way to get the line number if the tree does not contain the required values.

Things you might want to consider:

  • Improve your XML schema to catch missing information during parsing. Because @JohnZwinck already pointed out that line numbers still exist on parsing. You should definitely be able to exclude "that the person creating the xml decided to change [something structurally]" like this. You do this as if they are responsible for how the XML should look. Even so, your program still expects XML to be generated in a certain way to do important things with it. And here your game comes into play. Now, if they decide to change their circuit, you will immediately notice where there is a mismatch of the circuit that you developed.
  • Use another option get<string> . There are many options that allow you to specify default values, get zero, or do something else if the expected data does not exist.
    Your template template try-instant-catch-debug-continue assumes that you are not quite sure what data to expect, and that this is not critical if there is no data. Exceptions for exceptional situations. It seems to me that this is not one.
0
source share

All Articles