deprecateddomcount.cpp

来自「IBM的解析xml的工具Xerces的源代码」· C++ 代码 · 共 347 行

CPP
347
字号
/* * Copyright 1999-2001,2004 The Apache Software Foundation. *  * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *  *      http://www.apache.org/licenses/LICENSE-2.0 *  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *//* * $Id: DeprecatedDOMCount.cpp,v 1.8 2004/09/08 13:57:03 peiyongz Exp $ */// ---------------------------------------------------------------------------//  Includes// ---------------------------------------------------------------------------#include <xercesc/util/PlatformUtils.hpp>#include <xercesc/sax/SAXException.hpp>#include <xercesc/sax/SAXParseException.hpp>#include <xercesc/dom/deprecated/DOMParser.hpp>#include <xercesc/dom/deprecated/DOM_DOMException.hpp>#include "DeprecatedDOMCount.hpp"#include <string.h>#include <stdlib.h>#if defined(XERCES_NEW_IOSTREAMS)#include <fstream>#else#include <fstream.h>#endif#include <xercesc/util/OutOfMemoryException.hpp>// ---------------------------------------------------------------------------//  This is a simple program which invokes the DOMParser to build a DOM//  tree for the specified input file. It then walks the tree and counts//  the number of elements. The element count is then printed.// ---------------------------------------------------------------------------void usage(){    XERCES_STD_QUALIFIER cout << "\nUsage:\n"            "    DeprecatedDOMCount [options] <XML file | List file>\n\n"            "This program invokes the DOM parser, builds the DOM tree,\n"            "and then prints the number of elements found in each XML file.\n\n"            "Options:\n"            "    -l          Indicate the input file is a List File that has a list of xml files.\n"            "                Default to off (Input file is an XML file).\n"            "    -v=xxx      Validation scheme [always | never | auto*].\n"            "    -n          Enable namespace processing. Defaults to off.\n"            "    -s          Enable schema processing. Defaults to off.\n"            "    -f          Enable full schema constraint checking. Defaults to off.\n"		      "    -?          Show this help.\n\n"            "  * = Default if not provided explicitly.\n"         << XERCES_STD_QUALIFIER endl;}int main(int argC, char* argV[]){    // Initialize the XML4C system    try    {        XMLPlatformUtils::Initialize();    }    catch (const XMLException& toCatch)    {         XERCES_STD_QUALIFIER cerr << "Error during initialization! :\n"              << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;         return 1;    }    // Check command line and extract arguments.    if (argC < 2)    {        usage();        XMLPlatformUtils::Terminate();        return 1;    }    const char*              xmlFile = 0;    DOMParser::ValSchemes    valScheme = DOMParser::Val_Auto;    bool                     doNamespaces       = false;    bool                     doSchema           = false;    bool                     schemaFullChecking = false;    bool                     doList = false;    bool                     errorOccurred = false;    int argInd;    for (argInd = 1; argInd < argC; argInd++)    {        // Break out on first parm not starting with a dash        if (argV[argInd][0] != '-')            break;        // Watch for special case help request        if (!strcmp(argV[argInd], "-?"))        {            usage();            XMLPlatformUtils::Terminate();            return 2;        }         else if (!strncmp(argV[argInd], "-v=", 3)              ||  !strncmp(argV[argInd], "-V=", 3))        {            const char* const parm = &argV[argInd][3];            if (!strcmp(parm, "never"))                valScheme = DOMParser::Val_Never;            else if (!strcmp(parm, "auto"))                valScheme = DOMParser::Val_Auto;            else if (!strcmp(parm, "always"))                valScheme = DOMParser::Val_Always;            else            {                XERCES_STD_QUALIFIER cerr << "Unknown -v= value: " << parm << XERCES_STD_QUALIFIER endl;                return 2;            }        }         else if (!strcmp(argV[argInd], "-n")              ||  !strcmp(argV[argInd], "-N"))        {            doNamespaces = true;        }         else if (!strcmp(argV[argInd], "-s")              ||  !strcmp(argV[argInd], "-S"))        {            doSchema = true;        }         else if (!strcmp(argV[argInd], "-f")              ||  !strcmp(argV[argInd], "-F"))        {            schemaFullChecking = true;        }         else if (!strcmp(argV[argInd], "-l")              ||  !strcmp(argV[argInd], "-L"))        {            doList = true;        }         else if (!strcmp(argV[argInd], "-special:nel"))        {            // turning this on will lead to non-standard compliance behaviour            // it will recognize the unicode character 0x85 as new line character            // instead of regular character as specified in XML 1.0            // do not turn this on unless really necessary            XMLPlatformUtils::recognizeNEL(true);        }         else        {            XERCES_STD_QUALIFIER cerr << "Unknown option '" << argV[argInd]                 << "', ignoring it\n" << XERCES_STD_QUALIFIER endl;        }    }    //    //  There should be only one and only one parameter left, and that    //  should be the file name.    //    if (argInd != argC - 1)    {        usage();        return 1;    }    // Instantiate the DOM parser.    DOMParser* parser = new DOMParser;    parser->setValidationScheme(valScheme);    parser->setDoNamespaces(doNamespaces);    parser->setDoSchema(doSchema);    parser->setValidationSchemaFullChecking(schemaFullChecking);    // And create our error handler and install it    DeprecatedDOMCountErrorHandler errorHandler;    parser->setErrorHandler(&errorHandler);    //    //  Get the starting time and kick off the parse of the indicated    //  file. Catch any exceptions that might propogate out of it.    //    unsigned long duration;    bool more = true;    XERCES_STD_QUALIFIER ifstream fin;    // the input is a list file    if (doList)        fin.open(argV[argInd]);    if (fin.fail()) {        XERCES_STD_QUALIFIER cerr <<"Cannot open the list file: " << argV[argInd] << XERCES_STD_QUALIFIER endl;        return 2;    }    while (more)    {        char fURI[1000];        //initialize the array to zeros        memset(fURI,0,sizeof(fURI));        if (doList) {            if (! fin.eof() ) {                fin.getline (fURI, sizeof(fURI));                if (!*fURI)                    continue;                else {                    xmlFile = fURI;                    XERCES_STD_QUALIFIER cerr << "==Parsing== " << xmlFile << XERCES_STD_QUALIFIER endl;                }            }            else                break;        }        else {            xmlFile = argV[argInd];            more = false;        }        //reset error count first        errorHandler.resetErrors();        try        {            const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();            parser->parse(xmlFile);            const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();            duration = endMillis - startMillis;        }        catch (const OutOfMemoryException&)        {            XERCES_STD_QUALIFIER cerr << "OutOfMemoryException during parsing: '" << xmlFile << "'\n" << XERCES_STD_QUALIFIER endl;            errorOccurred = true;            continue;        }        catch (const XMLException& toCatch)        {            XERCES_STD_QUALIFIER cerr << "\nError during parsing: '" << xmlFile << "'\n"                 << "Exception message is:  \n"                 << StrX(toCatch.getMessage()) << "\n" << XERCES_STD_QUALIFIER endl;            errorOccurred = true;            continue;        }        catch (const DOM_DOMException& toCatch)        {            XERCES_STD_QUALIFIER cerr << "\nDOM Error during parsing: '" << xmlFile << "'\n"                 << "DOMException code is:  \n"                 << toCatch.code << "\n" << XERCES_STD_QUALIFIER endl;            errorOccurred = true;            continue;        }        catch (...)        {            XERCES_STD_QUALIFIER cerr << "\nUnexpected exception during parsing: '" << xmlFile << "'\n";            errorOccurred = true;            continue;        }        //        //  Extract the DOM tree, get the list of all the elements and report the        //  length as the count of elements.        //        if (errorHandler.getSawErrors())        {            XERCES_STD_QUALIFIER cout << "\nErrors occurred, no output available\n" << XERCES_STD_QUALIFIER endl;            errorOccurred = true;        }         else        {            DOM_Document doc = parser->getDocument();            unsigned int elementCount = doc.getElementsByTagName("*").getLength();            // Print out the stats that we collected and time taken.            XERCES_STD_QUALIFIER cout << xmlFile << ": " << duration << " ms ("                 << elementCount << " elems)." << XERCES_STD_QUALIFIER endl;        }    }    if (doList)        fin.close();    //    //  Delete the parser itself.  Must be done prior to calling Terminate, below.    //    delete parser;    // And call the termination method    XMLPlatformUtils::Terminate();    if (errorOccurred)        return 4;    else        return 0;}DeprecatedDOMCountErrorHandler::DeprecatedDOMCountErrorHandler() :    fSawErrors(false){}DeprecatedDOMCountErrorHandler::~DeprecatedDOMCountErrorHandler(){}// ---------------------------------------------------------------------------//  DeprecatedDOMCountHandlers: Overrides of the SAX ErrorHandler interface// ---------------------------------------------------------------------------void DeprecatedDOMCountErrorHandler::error(const SAXParseException& e){    fSawErrors = true;    XERCES_STD_QUALIFIER cerr << "\nError at file " << StrX(e.getSystemId())         << ", line " << e.getLineNumber()         << ", char " << e.getColumnNumber()         << "\n  Message: " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;}void DeprecatedDOMCountErrorHandler::fatalError(const SAXParseException& e){    fSawErrors = true;    XERCES_STD_QUALIFIER cerr << "\nFatal Error at file " << StrX(e.getSystemId())         << ", line " << e.getLineNumber()         << ", char " << e.getColumnNumber()         << "\n  Message: " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;}void DeprecatedDOMCountErrorHandler::warning(const SAXParseException& e){    XERCES_STD_QUALIFIER cerr << "\nWarning at file " << StrX(e.getSystemId())         << ", line " << e.getLineNumber()         << ", char " << e.getColumnNumber()         << "\n  Message: " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;}void DeprecatedDOMCountErrorHandler::resetErrors(){    fSawErrors = false;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?