diff --git a/src/xmlParser.cpp b/src/xmlParser.cpp index 4b46d86..d4ff3cf 100644 --- a/src/xmlParser.cpp +++ b/src/xmlParser.cpp @@ -73,6 +73,8 @@ **************************************************************************** */ +#include +#include // Component produces warning messages that were disabled only for this file. #pragma warning(disable : 4706) #pragma warning(disable : 4100) @@ -745,6 +747,51 @@ namespace XMLParser return xnode; } + XMLNode XMLNode::openFileHelperThrows(XMLCSTR filename, XMLCSTR tag) + { + // guess the value of the global parameter "characterEncoding" + // (the guess is based on the first 200 bytes of the file). + FILE * f; + errno_t err; + err = fopen_s(&f, filename, "rb"); + if(err) + { + char buff[2000]; + strerror_s(buff, err); + throw std::runtime_error(buff); + } + if(f) + { + char bb[205]; + int l = (int)fread(bb, 1, 200, f); + XMLNode::setGlobalOptions( + XMLNode::guessCharEncoding(bb, l), 1, 1, 1); + fclose(f); + } + + // parse the file + XMLResults results; + XMLNode node = XMLNode::parseFile(filename, tag, &results); + + // display error message (if any) + if(results.error != eXMLErrorNone) + { + std::stringstream msg; + + msg << "XML Parsing error in file: " << filename << " " + << XMLNode::getError(results.error) << " in line: " << results.nLine + << ", column: " << results.nColumn; + + if(results.error == eXMLErrorFirstTagNotFound) + { + msg << " First Tag should be " << tag; + } + + throw std::runtime_error(msg.str()); + } + return node; + } + ///////////////////////////////////////////////////////////////////////// // Here start the core implementation of the XMLParser library // ///////////////////////////////////////////////////////////////////////// diff --git a/src/xmlParser.h b/src/xmlParser.h index 67f3e63..ed6d6d4 100644 --- a/src/xmlParser.h +++ b/src/xmlParser.h @@ -310,6 +310,8 @@ namespace XMLParser { * @param tag the name of the first tag inside the XML file. If the tag parameter is omitted, this function returns a node that represents the head of the xml document including the declaration term (). */ + static XMLNode openFileHelperThrows(XMLCSTR filename, XMLCSTR tag = NULL); + static XMLCSTR getError(XMLError error); ///< this gives you a user-friendly explanation of the parsing error /// Create an XML string starting from the current XMLNode.