MemParse.cpp
上传用户:zhuqijet
上传日期:2013-06-25
资源大小:10074k
文件大小:12k
源码类别:

词法分析

开发平台:

Visual C++

  1. /*
  2.  * The Apache Software License, Version 1.1
  3.  *
  4.  * Copyright (c) 1999-2001 The Apache Software Foundation.  All rights
  5.  * reserved.
  6.  *
  7.  * Redistribution and use in source and binary forms, with or without
  8.  * modification, are permitted provided that the following conditions
  9.  * are met:
  10.  *
  11.  * 1. Redistributions of source code must retain the above copyright
  12.  *    notice, this list of conditions and the following disclaimer.
  13.  *
  14.  * 2. Redistributions in binary form must reproduce the above copyright
  15.  *    notice, this list of conditions and the following disclaimer in
  16.  *    the documentation and/or other materials provided with the
  17.  *    distribution.
  18.  *
  19.  * 3. The end-user documentation included with the redistribution,
  20.  *    if any, must include the following acknowledgment:
  21.  *       "This product includes software developed by the
  22.  *        Apache Software Foundation (http://www.apache.org/)."
  23.  *    Alternately, this acknowledgment may appear in the software itself,
  24.  *    if and wherever such third-party acknowledgments normally appear.
  25.  *
  26.  * 4. The names "Xerces" and "Apache Software Foundation" must
  27.  *    not be used to endorse or promote products derived from this
  28.  *    software without prior written permission. For written
  29.  *    permission, please contact apache@apache.org.
  30.  *
  31.  * 5. Products derived from this software may not be called "Apache",
  32.  *    nor may "Apache" appear in their name, without prior written
  33.  *    permission of the Apache Software Foundation.
  34.  *
  35.  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  36.  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37.  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  38.  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  39.  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40.  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41.  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  42.  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  43.  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  44.  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  45.  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  46.  * SUCH DAMAGE.
  47.  * ====================================================================
  48.  *
  49.  * This software consists of voluntary contributions made by many
  50.  * individuals on behalf of the Apache Software Foundation, and was
  51.  * originally based on software copyright (c) 1999, International
  52.  * Business Machines, Inc., http://www.ibm.com .  For more information
  53.  * on the Apache Software Foundation, please see
  54.  * <http://www.apache.org/>.
  55.  */
  56. /*
  57.  * $Log: MemParse.cpp,v $
  58.  * Revision 1.13  2002/02/01 22:37:14  peiyongz
  59.  * sane_include
  60.  *
  61.  * Revision 1.12  2001/10/25 15:18:33  tng
  62.  * delete the parser before XMLPlatformUtils::Terminate.
  63.  *
  64.  * Revision 1.11  2001/10/19 18:56:08  tng
  65.  * Pulled the hardcoded "encoding" out of the document itself and made it a #define
  66.  * to make it easier to support other encodings.  Patch from David McCreedy.
  67.  * And other modification for consistent help display and return code across samples.
  68.  *
  69.  * Revision 1.10  2001/08/01 19:11:01  tng
  70.  * Add full schema constraint checking flag to the samples and the parser.
  71.  *
  72.  * Revision 1.9  2001/05/11 13:24:55  tng
  73.  * Copyright update.
  74.  *
  75.  * Revision 1.8  2001/05/03 15:59:40  tng
  76.  * Schema: samples update with schema
  77.  *
  78.  * Revision 1.7  2000/09/11 18:43:48  aruna1
  79.  * OS390 related updates
  80.  *
  81.  * Revision 1.6  2000/03/02 19:53:42  roddey
  82.  * This checkin includes many changes done while waiting for the
  83.  * 1.1.0 code to be finished. I can't list them all here, but a list is
  84.  * available elsewhere.
  85.  *
  86.  * Revision 1.5  2000/02/11 02:37:01  abagchi
  87.  * Removed StrX::transcode
  88.  *
  89.  * Revision 1.4  2000/02/06 07:47:19  rahulj
  90.  * Year 2K copyright swat.
  91.  *
  92.  * Revision 1.3  2000/01/12 00:27:00  roddey
  93.  * Updates to work with the new URL and input source scheme.
  94.  *
  95.  * Revision 1.2  1999/11/20 01:09:55  rahulj
  96.  * Fixed usage message.
  97.  *
  98.  * Revision 1.1.1.1  1999/11/09 01:09:49  twl
  99.  * Initial checkin
  100.  *
  101.  * Revision 1.7  1999/11/08 20:43:36  rahul
  102.  * Swat for adding in Product name and CVS comment log variable.
  103.  *
  104.  */
  105. /**
  106.  * This sample program illustrates how one can use a memory buffer as the
  107.  * input to parser. The memory buffer contains raw bytes representing XML
  108.  * statements.
  109.  *
  110.  * Look at the API documentation for 'MemBufInputSource' for more information
  111.  * on parameters to the constructor.
  112.  *
  113.  */
  114. // ---------------------------------------------------------------------------
  115. //  Includes
  116. // ---------------------------------------------------------------------------
  117. #include <xercesc/parsers/SAXParser.hpp>
  118. #include <xercesc/framework/MemBufInputSource.hpp>
  119. #include "MemParse.hpp"
  120. // ---------------------------------------------------------------------------
  121. //  Local const data
  122. //
  123. //  gXMLInMemBuf
  124. //      Defines the memory buffer contents here which parsed by the XML
  125. //      parser. This is the cheap way to do it, instead of reading it from
  126. //      somewhere. For this demo, its fine.
  127. //
  128. //      NOTE: If your encoding is not ascii you will need to change
  129. //            the MEMPARSE_ENCODING #define
  130. //
  131. //  gMemBufId
  132. //      A simple name to give as the system id for the memory buffer. This
  133. //      just for indentification purposes in case of errors. Its not a real
  134. //      system id (and the parser knows that.)
  135. // ---------------------------------------------------------------------------
  136. #ifndef MEMPARSE_ENCODING
  137.    #if defined(OS390)
  138.       #define MEMPARSE_ENCODING "ibm-1047-s390"
  139.    #else
  140.       #define MEMPARSE_ENCODING "ascii"
  141.    #endif
  142. #endif /* ifndef MEMPARSE_ENCODING */
  143. static const char*  gXMLInMemBuf =
  144. "
  145. <?xml version='1.0' encoding='" MEMPARSE_ENCODING "'?>n
  146. <!DOCTYPE company [n
  147. <!ELEMENT company     (product,category,developedAt)>n
  148. <!ELEMENT product     (#PCDATA)>n
  149. <!ELEMENT category    (#PCDATA)>n
  150. <!ATTLIST category idea CDATA #IMPLIED>n
  151. <!ELEMENT developedAt (#PCDATA)>n
  152. ]>nn
  153. <company>n
  154.     <product>XML4C</product>n
  155.     <category idea='great'>XML Parsing Tools</category>n
  156.     <developedAt>n
  157.       IBM Center for Java Technology, Silicon Valley, Cupertino, CAn
  158.     </developedAt>n
  159. </company>
  160. ";
  161. static const char*  gMemBufId = "prodInfo";
  162. // ---------------------------------------------------------------------------
  163. //  Local helper methods
  164. // ---------------------------------------------------------------------------
  165. void usage()
  166. {
  167.     cout << "nUsage:n"
  168.             "    MemParse [options]nn"
  169.             "This program uses the SAX Parser to parse a memory buffern"
  170.             "containing XML statements, and reports the number ofn"
  171.             "elements and attributes found.nn"
  172.             "Options:n"
  173.             "    -v=xxx      Validation scheme [always | never | auto*].n"
  174.             "    -n          Enable namespace processing. Defaults to off.n"
  175.             "    -s          Enable schema processing. Defaults to off.n"
  176.             "    -f          Enable full schema constraint checking. Defaults to off.n"
  177.       "    -?          Show this help.nn"
  178.             "  * = Default if not provided explicitly.n"
  179.          << endl;
  180. }
  181. // ---------------------------------------------------------------------------
  182. //  Program entry point
  183. // ---------------------------------------------------------------------------
  184. int main(int argC, char* argV[])
  185. {
  186.     // Initialize the XML4C2 system
  187.     try
  188.     {
  189.          XMLPlatformUtils::Initialize();
  190.     }
  191.     catch (const XMLException& toCatch)
  192.     {
  193.          cerr << "Error during initialization! Message:n"
  194.               << StrX(toCatch.getMessage()) << endl;
  195.          return 1;
  196.     }
  197.     SAXParser::ValSchemes    valScheme = SAXParser::Val_Auto;
  198.     bool doNamespaces       = false;
  199.     bool doSchema           = false;
  200.     bool schemaFullChecking = false;
  201.     int argInd;
  202.     for (argInd = 1; argInd < argC; argInd++)
  203.     {
  204.         // Break out on first parm not starting with a dash
  205.         if (argV[argInd][0] != '-')
  206.         {
  207.             usage();
  208.             XMLPlatformUtils::Terminate();
  209.             return 1;
  210.         }
  211.         // Watch for special case help request
  212.         if (!strcmp(argV[argInd], "-?"))
  213.         {
  214.             usage();
  215.             XMLPlatformUtils::Terminate();
  216.             return 1;
  217.         }
  218.          else if (!strncmp(argV[argInd], "-v=", 3)
  219.               ||  !strncmp(argV[argInd], "-V=", 3))
  220.         {
  221.             const char* const parm = &argV[argInd][3];
  222.             if (!strcmp(parm, "never"))
  223.                 valScheme = SAXParser::Val_Never;
  224.             else if (!strcmp(parm, "auto"))
  225.                 valScheme = SAXParser::Val_Auto;
  226.             else if (!strcmp(parm, "always"))
  227.                 valScheme = SAXParser::Val_Always;
  228.             else
  229.             {
  230.                 cerr << "Unknown -v= value: " << parm << endl;
  231.                 return 2;
  232.             }
  233.         }
  234.          else if (!strcmp(argV[argInd], "-n")
  235.               ||  !strcmp(argV[argInd], "-N"))
  236.         {
  237.             doNamespaces = true;
  238.         }
  239.          else if (!strcmp(argV[argInd], "-s")
  240.               ||  !strcmp(argV[argInd], "-S"))
  241.         {
  242.             doSchema = true;
  243.         }
  244.          else if (!strcmp(argV[argInd], "-f")
  245.               ||  !strcmp(argV[argInd], "-F"))
  246.         {
  247.             schemaFullChecking = true;
  248.         }
  249.          else
  250.         {
  251.             cerr << "Unknown option '" << argV[argInd]
  252.                  << "', ignoring itn" << endl;
  253.         }
  254.     }
  255.     //
  256.     //  Create a SAX parser object. Then, according to what we were told on
  257.     //  the command line, set it to validate or not.
  258.     //
  259.     SAXParser* parser = new SAXParser;
  260.     parser->setValidationScheme(valScheme);
  261.     parser->setDoNamespaces(doNamespaces);
  262.     parser->setDoSchema(doSchema);
  263.     parser->setValidationSchemaFullChecking(schemaFullChecking);
  264.     //
  265.     //  Create our SAX handler object and install it on the parser, as the
  266.     //  document and error handlers.
  267.     //
  268.     MemParseHandlers handler;
  269.     parser->setDocumentHandler(&handler);
  270.     parser->setErrorHandler(&handler);
  271.     //
  272.     //  Create MemBufferInputSource from the buffer containing the XML
  273.     //  statements.
  274.     //
  275.     //  NOTE: We are using strlen() here, since we know that the chars in
  276.     //  our hard coded buffer are single byte chars!!! The parameter wants
  277.     //  the number of BYTES, not chars, so when you create a memory buffer
  278.     //  give it the byte size (which just happens to be the same here.)
  279.     //
  280.     MemBufInputSource* memBufIS = new MemBufInputSource
  281.     (
  282.         (const XMLByte*)gXMLInMemBuf
  283.         , strlen(gXMLInMemBuf)
  284.         , gMemBufId
  285.         , false
  286.     );
  287.     //
  288.     //  Get the starting time and kick off the parse of the indicated
  289.     //  file. Catch any exceptions that might propogate out of it.
  290.     //
  291.     unsigned long duration;
  292.     int errorCount = 0;
  293.     try
  294.     {
  295.         const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
  296.         parser->parse(*memBufIS);
  297.         const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
  298.         duration = endMillis - startMillis;
  299.         errorCount = parser->getErrorCount();
  300.     }
  301.     catch (const XMLException& e)
  302.     {
  303.         cerr << "nError during parsing memory stream:n"
  304.              << "Exception message is:  n"
  305.              << StrX(e.getMessage()) << "n" << endl;
  306.         return 4;
  307.     }
  308.     // Print out the stats that we collected and time taken.
  309.     if (!errorCount) {
  310.         cout << "nFinished parsing the memory buffer containing the following "
  311.              << "XML statements:nn"
  312.              << gXMLInMemBuf
  313.              << "nnn"
  314.              << "Parsing took " << duration << " ms ("
  315.              << handler.getElementCount() << " elements, "
  316.              << handler.getAttrCount() << " attributes, "
  317.              << handler.getSpaceCount() << " spaces, "
  318.              << handler.getCharacterCount() << " characters).n" << endl;
  319.     }
  320.     //
  321.     //  Delete the parser itself.  Must be done prior to calling Terminate, below.
  322.     //
  323.     delete parser;
  324.     delete memBufIS;
  325.     // And call the termination method
  326.     XMLPlatformUtils::Terminate();
  327.     if (errorCount > 0)
  328.         return 4;
  329.     else
  330.         return 0;
  331. }