Beispiel #1
0
 /// Dump DOM tree using XercesC handles
 void dumpTree(DOMNode* doc, ostream& os) {
   if ( doc )  {
     DOMImplementation  *imp = DOMImplementationRegistry::getDOMImplementation(Strng_t("LS"));
     MemBufFormatTarget *tar = new MemBufFormatTarget();
     DOMLSOutput        *out = imp->createLSOutput();
     DOMLSSerializer    *wrt = imp->createLSSerializer();
     out->setByteStream(tar);
     wrt->getDomConfig()->setParameter(Strng_t("format-pretty-print"), true);
     wrt->write(doc, out);
     os << tar->getRawBuffer() << endl << flush;
     out->release();
     wrt->release();
     return;
   }
   printout(ERROR,"dumpTree","+++ Cannot dump invalid document.");
 }
int XmlParser::commit(const char* xmlFile) {
   try {
      // Obtain DOM implementation supporting Load/Save
      DOMImplementationLS* pImplementation = dynamic_cast<DOMImplementationLS *>(DOMImplementationRegistry::getDOMImplementation(DualString("LS").asXMLString()));
      if (pImplementation == NULL){
         throw( std::runtime_error( "Unable to obtain suitable DOMImplementation!" ) ) ;
      }

      DOMLSSerializer *pSerializer = pImplementation->createLSSerializer();

      DOMLSOutput *pOutput = pImplementation->createLSOutput();
#if 1
      // Change output format to be pretty (but it isn't)
      DOMConfiguration *pConfiguration = pSerializer->getDomConfig();
      if (pConfiguration->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
         pConfiguration->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);
#if 0
      // Overrides above but seems to have little effect!
      if (pConfiguration->canSetParameter(XMLUni::fgDOMWRTCanonicalForm, true))
         pConfiguration->setParameter(XMLUni::fgDOMWRTCanonicalForm, true);
#endif
#if 1
      //
      if (pConfiguration->canSetParameter(XMLUni::fgDOMWRTEntities, true))
         pConfiguration->setParameter(XMLUni::fgDOMWRTEntities, true);
#endif
#endif
      LocalFileFormatTarget *pTarget = new LocalFileFormatTarget(DualString( xmlFile ).asXMLString());
      pOutput->setByteStream(pTarget);

//      mergeDocument->normalizeDocument(); // Needed?
      pSerializer->write(mergeDocument, pOutput);

      delete pTarget;
      pOutput->release();
      pSerializer->release();

   } catch( const xercesc::XMLException& e ){
      return -1;
   }

   return 0;
}
void PrintXMLdoc(const XERCES_CPP_NAMESPACE::DOMDocument* doc)
{
	DOMImplementation* impl =  DOMImplementationRegistry::getDOMImplementation(L"Core");
	DOMLSSerializer   *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
    DOMLSOutput       *theOutputDesc = ((DOMImplementationLS*)impl)->createLSOutput();
	
	DOMConfiguration* serializerConfig=theSerializer->getDomConfig();
	if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
		serializerConfig->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);

	XMLFormatTarget *outputStream = new StdOutFormatTarget();
	theOutputDesc->setByteStream(outputStream);

	theSerializer->write(doc, theOutputDesc);

    theOutputDesc->release();
    theSerializer->release();

	delete outputStream;
}
Beispiel #4
0
bool XMLIO::Write (DOMImplementation* impl, DOMNode* node, string filename) {

	XMLFormatTarget* mft;

	if (filename.empty())
		mft = new StdOutFormatTarget();
	else
		mft = new LocalFileFormatTarget (StrX(filename).XMLchar());

	// Xerces 2
    #ifdef XSEC_XERCES_HAS_SETIDATTRIBUTE
	DOMWriter* serializer = ((DOMImplementationLS*)impl)->createDOMWriter();

    if (serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true))
		serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true);
	
	serializer->writeNode(mft, *node);

	serializer->release();
    #endif 

    #ifdef XSEC_XERCES_HAS_BOOLSETIDATTRIBUTE
	DOMLSSerializer*   serializer    = ((DOMImplementationLS*) impl)->createLSSerializer();
	DOMLSOutput*       output        = ((DOMImplementationLS*)impl)->createLSOutput(); 
    DOMConfiguration*  configuration = serializer->getDomConfig(); 

	if (configuration->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
		configuration->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true); 

	output->setByteStream (mft);
	serializer->write(node, output);

	output->release();
	serializer->release(); 
    #endif

	return true;

}
Beispiel #5
0
//save the document to an external file
void ResultXML::save()
{
    //create the serializer for saving the document
    DOMLSSerializer *serializer = (DOMLSSerializer*)imp->createLSSerializer();

    //configure for saving it in a well presented human readable format
    if(serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true)){
       serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);
    }

    //set the output for serializing as a stream
    DOMLSOutput *output = ((DOMImplementationLS*)imp)->createLSOutput();
    output->setByteStream(ftarget);

    //use the serializer to save the document and catch any errors encountered
    try{
        serializer->write(root, output);
    }
    catch (const XMLException& e) {
        char* msg = XMLString::transcode(e.getMessage());
        cout << "Error Exception Encountered: " << endl << msg << endl;
        XMLString::release(&msg);
    }
    catch (const DOMException& e) {
        char* msg = XMLString::transcode(e.getMessage());
        cout << "Error Exception Encountered: " << endl << msg << endl;
        XMLString::release(&msg);
    }
    catch (...) {
        cout << "Error Unknown Exception" << endl;
    }

    //force the release of resources held by the serializer and output manager
    output->release();
    serializer->release();
}
Beispiel #6
0
void OutputXML(xercesc::DOMDocument* pmyDOMDocument, std::string filePath) 
{ 
	//Return the first registered implementation that has the desired features. In this case, we are after a DOM implementation that has the LS feature... or Load/Save. 
	DOMImplementation *implementation = DOMImplementationRegistry::getDOMImplementation(XMLString::transcode("LS"));

	// Create a DOMLSSerializer which is used to serialize a DOM tree into an XML document. 
	DOMLSSerializer *serializer = ((DOMImplementationLS*)implementation)->createLSSerializer(); 

	// Make the output more human readable by inserting line feeds. 
	if (serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true)) 
		serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true); 

	// The end-of-line sequence of characters to be used in the XML being written out.  
	serializer->setNewLine(XMLString::transcode("\r\n"));  

	// Convert the path into Xerces compatible XMLCh*. 
	XMLCh *tempFilePath = XMLString::transcode(filePath.c_str()); 

	// Specify the target for the XML output. 
	XMLFormatTarget *formatTarget = new LocalFileFormatTarget(tempFilePath); 

	// Create a new empty output destination object. 
	DOMLSOutput *output = ((DOMImplementationLS*)implementation)->createLSOutput(); 

	// Set the stream to our target. 
	output->setByteStream(formatTarget); 

	// Write the serialized output to the destination. 
	serializer->write(pmyDOMDocument, output); 

	// Cleanup. 
	serializer->release(); 
	XMLString::release(&tempFilePath); 
	delete formatTarget; 
	output->release(); 
} 
Beispiel #7
0
// ---------------------------------------------------------------------------
//
//   main
//
// ---------------------------------------------------------------------------
int main(int argC, char* argV[])
{
	char						*testFileName;
	char						*outputFileName;

    for (int argInd = 1; argInd < argC; argInd++)
	{
        if (!strcmp(argV[argInd], "-?") || !strcmp(argV[argInd], "-h"))
        {
			/* print help and exit */
            usage();
            return 2;
        }
    }

	if (argC < 3){
		usage();
		return 2;
	}

	testFileName = argV[argC-2];
	outputFileName = argV[argC-1];

    // 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;
    }

	//============================================================================
	// Instantiate the DOM parser to use for the source documents
	//============================================================================
    static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };
    DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(gLS);
    DOMLSParser       *parser = ((DOMImplementationLS*)impl)->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS, 0);
    DOMConfiguration  *config = parser->getDomConfig();

    config->setParameter(XMLUni::fgDOMNamespaces, true);
    config->setParameter(XMLUni::fgXercesSchema, true);
    config->setParameter(XMLUni::fgXercesSchemaFullChecking, true);

	if(config->canSetParameter(XMLUni::fgXercesDoXInclude, true)){
		config->setParameter(XMLUni::fgXercesDoXInclude, true);
	}
    
    // enable datatype normalization - default is off
    //config->setParameter(XMLUni::fgDOMDatatypeNormalization, true);

    // And create our error handler and install it
    XIncludeErrorHandler errorHandler;
    config->setParameter(XMLUni::fgDOMErrorHandler, &errorHandler);

    XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument *doc = 0;

    try
    {
        // load up the test source document
		XERCES_STD_QUALIFIER cerr << "Parse " << testFileName << " in progress ...";
        parser->resetDocumentPool();
		doc = parser->parseURI(testFileName);
		XERCES_STD_QUALIFIER cerr << " finished." << XERCES_STD_QUALIFIER endl;
    }
    catch (const XMLException& toCatch)
    {
        XERCES_STD_QUALIFIER cerr << "\nError during parsing: '" << testFileName << "'\n"
                << "Exception message is:  \n"
                << StrX(toCatch.getMessage()) << "\n" << XERCES_STD_QUALIFIER endl;
    }
    catch (const DOMException& toCatch)
    {
        const unsigned int maxChars = 2047;
        XMLCh errText[maxChars + 1];

        XERCES_STD_QUALIFIER cerr << "\nDOM Error during parsing: '" << testFileName << "'\n"
                << "DOMException code is:  " << toCatch.code << XERCES_STD_QUALIFIER endl;

        if (DOMImplementation::loadDOMExceptionMsg(toCatch.code, errText, maxChars))
                XERCES_STD_QUALIFIER cerr << "Message is: " << StrX(errText) << XERCES_STD_QUALIFIER endl;

    }
    catch (...)
    {
        XERCES_STD_QUALIFIER cerr << "\nUnexpected exception during parsing: '" << testFileName << "'\n";
    }

    if (!errorHandler.getSawErrors() && doc) {
	    DOMLSSerializer	*writer = ((DOMImplementationLS*)impl)->createLSSerializer();
	    DOMLSOutput     *theOutputDesc = ((DOMImplementationLS*)impl)->createLSOutput();

		try {
			// write out the results
			XERCES_STD_QUALIFIER cerr << "Writing result to: " << outputFileName << XERCES_STD_QUALIFIER endl;

			XMLFormatTarget *myFormTarget = new LocalFileFormatTarget(outputFileName);
			theOutputDesc->setByteStream(myFormTarget);
			writer->write(doc, theOutputDesc);
            delete myFormTarget;
		}
		catch (const XMLException& toCatch)
		{
		    XERCES_STD_QUALIFIER cerr << "\nXMLException during writing: '" << testFileName << "'\n"
				<< "Exception message is:  \n"
				<< StrX(toCatch.getMessage()) << "\n" << XERCES_STD_QUALIFIER endl;
		}
		catch (const DOMException& toCatch)
		{
			const unsigned int maxChars = 2047;
			XMLCh errText[maxChars + 1];

			XERCES_STD_QUALIFIER cerr << "\nDOM Error during writing: '" << testFileName << "'\n"
				<< "DOMException code is:  " << toCatch.code << XERCES_STD_QUALIFIER endl;

			if (DOMImplementation::loadDOMExceptionMsg(toCatch.code, errText, maxChars))
				XERCES_STD_QUALIFIER cerr << "Message is: " << StrX(errText) << XERCES_STD_QUALIFIER endl;
		}
		catch (...)
		{
			XERCES_STD_QUALIFIER cerr << "\nUnexpected exception during writing: '" << testFileName << "'\n";
		}
        writer->release();
        theOutputDesc->release();
    }

    //
    //  Delete the parser itself.  Must be done prior to calling Terminate, below.
    //
    parser->release();
	// And call the termination method
    XMLPlatformUtils::Terminate();

    return 0;
}
Beispiel #8
0
void CTibiaItem::saveItemLists()
{
	if (!xmlInitialised)
	{
		XMLPlatformUtils::Initialize();
		xmlInitialised = 1;
	}
	XercesDOMParser *parser = new XercesDOMParser();
	try
	{
		//int itemNr;
		char pathBuf[2048];
		sprintf(pathBuf, "%s\\data\\tibiaauto-items.xml", CInstallPath::getInstallPath().c_str());

		DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(XMLString::transcode("Core"));

		xercesc::DOMDocument *doc = impl->createDocument(0, XMLString::transcode("item-definitions"), 0);
		doc->createComment((const unsigned short *)"<!-- Tibia Items for Tibia -->");

		DOMElement *root = doc->getDocumentElement();

		//ITEMS
		DOMNode *itemsNode = doc->createElement(XMLString::transcode("items"));
		root->appendChild(itemsNode);
		//recursively save data structure to XML
		saveItemsBranch(itemsNode, itemTree, doc);

		//FOOD
		DOMNode *foodNode = doc->createElement(XMLString::transcode("foods"));
		root->appendChild(foodNode);
		{
			int size = foodList.GetCount();
			for (int i = 0; i < size; i++)
			{
				char buf[512];
				DOMElement*  itemElem = doc->createElement(XMLString::transcode("item"));
				foodNode->appendChild(itemElem);
				char* name = foodList.GetTextAtIndex(i);
				int id     = foodList.GetValueAtIndex(i);
				int time   = foodList.GetExtraInfoAtIndex(i);

				sprintf(buf, "0x%x", id);
				itemElem->setAttribute(XMLString::transcode("id"), XMLString::transcode(buf));

				itemElem->setAttribute(XMLString::transcode("name"), XMLString::transcode(name));

				sprintf(buf, "%d", time);
				itemElem->setAttribute(XMLString::transcode("time"), XMLString::transcode(buf));
			}
		}
		//CONSTS
		/* never any need to save constants anymore
		   DOMNode *constsNode = doc->createElement(XMLString::transcode("consts"));
		   root->appendChild(constsNode);
		   int size = constCodeList.GetCount();
		   for (int i=0;i<size;i++){
		   char buf[512];
		   DOMElement*  itemElem = doc->createElement(XMLString::transcode("const"));
		   constsNode->appendChild(itemElem);
		   char* code=constCodeList.GetTextAtIndex(i);
		   int value=constCodeList.GetValueAtIndex(i);

		   sprintf(buf, "0x%x", value);
		   itemElem->setAttribute(XMLString::transcode("value"), XMLString::transcode(buf));

		   itemElem->setAttribute(XMLString::transcode("code"), XMLString::transcode(code));
		   }
		 */

		XMLCh tempStr[100];
		XMLString::transcode("LS", tempStr, 99);

		impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
		DOMLSSerializer* theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
		DOMConfiguration* dc           = theSerializer->getDomConfig();
		if (dc->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
			dc->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);
		XMLFormatTarget *outFile = new LocalFileFormatTarget(pathBuf);
		DOMLSOutput *lsOut       = ((DOMImplementationLS*)impl)->createLSOutput();
		lsOut->setByteStream(outFile);
		theSerializer->write(doc, lsOut);
		theSerializer->release();
		lsOut->release();
		delete outFile;
	}
	catch (...)
	{
		AfxMessageBox("Unable to save item definitions!");
	}

	delete parser;
}
Beispiel #9
0
// ---------------------------------------------------------------------------
//
//  main
//
// ---------------------------------------------------------------------------
int main(int argC, char* argV[])
{
    int retval = 0;

    // Initialize the XML4C2 system
    try
    {
        XMLPlatformUtils::Initialize();
    }

    catch(const XMLException &toCatch)
    {
        XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n"
             << "  Exception message:"
             << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
        return 1;
    }

    // Check command line and extract arguments.
    if (argC < 2)
    {
        usage();
        XMLPlatformUtils::Terminate();
        return 1;
    }

    // See if non validating dom parser configuration is requested.
    int parmInd;
    for (parmInd = 1; parmInd < argC; parmInd++)
    {
        // Break out on first parm not starting with a dash
        if (argV[parmInd][0] != '-')
            break;

        // Watch for special case help request
        if (!strcmp(argV[parmInd], "-?"))
        {
            usage();
            XMLPlatformUtils::Terminate();
            return 2;
        }
         else if (!strncmp(argV[parmInd], "-v=", 3)
              ||  !strncmp(argV[parmInd], "-V=", 3))
        {
            const char* const parm = &argV[parmInd][3];

            if (!strcmp(parm, "never"))
                gValScheme = XercesDOMParser::Val_Never;
            else if (!strcmp(parm, "auto"))
                gValScheme = XercesDOMParser::Val_Auto;
            else if (!strcmp(parm, "always"))
                gValScheme = XercesDOMParser::Val_Always;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -v= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }
        }
         else if (!strcmp(argV[parmInd], "-n")
              ||  !strcmp(argV[parmInd], "-N"))
        {
            gDoNamespaces = true;
        }
         else if (!strcmp(argV[parmInd], "-s")
              ||  !strcmp(argV[parmInd], "-S"))
        {
            gDoSchema = true;
        }
         else if (!strcmp(argV[parmInd], "-f")
              ||  !strcmp(argV[parmInd], "-F"))
        {
            gSchemaFullChecking = true;
        }
         else if (!strcmp(argV[parmInd], "-e")
              ||  !strcmp(argV[parmInd], "-E"))
        {
            gDoCreate = true;
        }
         else if (!strncmp(argV[parmInd], "-wenc=", 6))
        {
             // Get out the encoding name
             gOutputEncoding = XMLString::transcode( &(argV[parmInd][6]) );
        }
         else if (!strncmp(argV[parmInd], "-wfile=", 7))
        {
             goutputfile =  &(argV[parmInd][7]);
        }
         else if (!strncmp(argV[parmInd], "-wddc=", 6))
        {
            const char* const parm = &argV[parmInd][6];

            if (!strcmp(parm, "on"))
				gDiscardDefaultContent = true;
            else if (!strcmp(parm, "off"))
				gDiscardDefaultContent = false;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -wddc= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }

        }
         else if (!strncmp(argV[parmInd], "-wscs=", 6))
        {
            const char* const parm = &argV[parmInd][6];

            if (!strcmp(parm, "on"))
				gSplitCdataSections = true;
			else if (!strcmp(parm, "off"))
				gSplitCdataSections = false;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -wscs= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }
        }
         else if (!strncmp(argV[parmInd], "-wflt=", 6))
        {
            const char* const parm = &argV[parmInd][6];

            if (!strcmp(parm, "on"))
				gUseFilter = true;
			else if (!strcmp(parm, "off"))
				gUseFilter = false;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -wflt= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }
        }
         else if (!strncmp(argV[parmInd], "-wfpp=", 6))
        {
            const char* const parm = &argV[parmInd][6];

            if (!strcmp(parm, "on"))
				gFormatPrettyPrint = true;
			else if (!strcmp(parm, "off"))
				gFormatPrettyPrint = false;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -wfpp= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }
        }
         else if (!strncmp(argV[parmInd], "-wbom=", 6))
        {
            const char* const parm = &argV[parmInd][6];

            if (!strcmp(parm, "on"))
                gWriteBOM = true;
            else if (!strcmp(parm, "off"))
                gWriteBOM = false;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -wbom= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }
        }
         else if (!strncmp(argV[parmInd], "-xpath=", 7))
        {
             gXPathExpression = &(argV[parmInd][7]);
        }
         else
        {
            XERCES_STD_QUALIFIER cerr << "Unknown option '" << argV[parmInd]
                 << "', ignoring it.\n" << XERCES_STD_QUALIFIER endl;
        }
    }

    //
    //  And now we have to have only one parameter left and it must be
    //  the file name.
    //
    if (parmInd + 1 != argC)
    {
        usage();
        XMLPlatformUtils::Terminate();
        return 1;
    }
    gXmlFile = argV[parmInd];

    //
    //  Create our parser, then attach an error handler to the parser.
    //  The parser will call back to methods of the ErrorHandler if it
    //  discovers errors during the course of parsing the XML document.
    //
    XercesDOMParser *parser = new XercesDOMParser;
    parser->setValidationScheme(gValScheme);
    parser->setDoNamespaces(gDoNamespaces);
    parser->setDoSchema(gDoSchema);
    parser->setValidationSchemaFullChecking(gSchemaFullChecking);
    parser->setCreateEntityReferenceNodes(gDoCreate);

    DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter();
    parser->setErrorHandler(errReporter);

    //
    //  Parse the XML file, catching any XML exceptions that might propogate
    //  out of it.
    //
    bool errorsOccured = false;
    try
    {
        parser->parse(gXmlFile);
    }
    catch (const OutOfMemoryException&)
    {
        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
        errorsOccured = true;
    }
    catch (const XMLException& e)
    {
        XERCES_STD_QUALIFIER cerr << "An error occurred during parsing\n   Message: "
             << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
        errorsOccured = true;
    }

    catch (const DOMException& e)
    {
        const unsigned int maxChars = 2047;
        XMLCh errText[maxChars + 1];

        XERCES_STD_QUALIFIER cerr << "\nDOM Error during parsing: '" << gXmlFile << "'\n"
             << "DOMException code is:  " << e.code << XERCES_STD_QUALIFIER endl;

        if (DOMImplementation::loadDOMExceptionMsg(e.code, errText, maxChars))
             XERCES_STD_QUALIFIER cerr << "Message is: " << StrX(errText) << XERCES_STD_QUALIFIER endl;

        errorsOccured = true;
    }

    catch (...)
    {
        XERCES_STD_QUALIFIER cerr << "An error occurred during parsing\n " << XERCES_STD_QUALIFIER endl;
        errorsOccured = true;
    }

    // If the parse was successful, output the document data from the DOM tree
    if (!errorsOccured && !errReporter->getSawErrors())
    {
        DOMPrintFilter   *myFilter = 0;

        try
        {
            // get a serializer, an instance of DOMLSSerializer
            XMLCh tempStr[3] = {chLatin_L, chLatin_S, chNull};
            DOMImplementation *impl          = DOMImplementationRegistry::getDOMImplementation(tempStr);
            DOMLSSerializer   *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
            DOMLSOutput       *theOutputDesc = ((DOMImplementationLS*)impl)->createLSOutput();

            // set user specified output encoding
            theOutputDesc->setEncoding(gOutputEncoding);

            // plug in user's own filter
            if (gUseFilter)
            {
                // even we say to show attribute, but the DOMLSSerializer
                // will not show attribute nodes to the filter as
                // the specs explicitly says that DOMLSSerializer shall
                // NOT show attributes to DOMLSSerializerFilter.
                //
                // so DOMNodeFilter::SHOW_ATTRIBUTE has no effect.
                // same DOMNodeFilter::SHOW_DOCUMENT_TYPE, no effect.
                //
                myFilter = new DOMPrintFilter(DOMNodeFilter::SHOW_ELEMENT   |
                                              DOMNodeFilter::SHOW_ATTRIBUTE |
                                              DOMNodeFilter::SHOW_DOCUMENT_TYPE);
                theSerializer->setFilter(myFilter);
            }

            // plug in user's own error handler
            DOMErrorHandler *myErrorHandler = new DOMPrintErrorHandler();
            DOMConfiguration* serializerConfig=theSerializer->getDomConfig();
            serializerConfig->setParameter(XMLUni::fgDOMErrorHandler, myErrorHandler);

            // set feature if the serializer supports the feature/mode
            if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTSplitCdataSections, gSplitCdataSections))
                serializerConfig->setParameter(XMLUni::fgDOMWRTSplitCdataSections, gSplitCdataSections);

            if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTDiscardDefaultContent, gDiscardDefaultContent))
                serializerConfig->setParameter(XMLUni::fgDOMWRTDiscardDefaultContent, gDiscardDefaultContent);

            if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, gFormatPrettyPrint))
                serializerConfig->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, gFormatPrettyPrint);

            if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTBOM, gWriteBOM))
                serializerConfig->setParameter(XMLUni::fgDOMWRTBOM, gWriteBOM);

            //
            // Plug in a format target to receive the resultant
            // XML stream from the serializer.
            //
            // StdOutFormatTarget prints the resultant XML stream
            // to stdout once it receives any thing from the serializer.
            //
            XMLFormatTarget *myFormTarget;
            if (goutputfile)
                myFormTarget=new LocalFileFormatTarget(goutputfile);
            else
                myFormTarget=new StdOutFormatTarget();
            theOutputDesc->setByteStream(myFormTarget);

            // get the DOM representation
            DOMDocument *doc = parser->getDocument();

            //
            // do the serialization through DOMLSSerializer::write();
            //
            if(gXPathExpression!=NULL)
            {
                XMLCh* xpathStr=XMLString::transcode(gXPathExpression);
                DOMElement* root = doc->getDocumentElement();
                try
                {
                    DOMXPathNSResolver* resolver=doc->createNSResolver(root);
                    DOMXPathResult* result=doc->evaluate(
                      xpathStr,
                      root,
                      resolver,
                      DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE,
                      NULL);

                    XMLSize_t nLength = result->getSnapshotLength();
                    for(XMLSize_t i = 0; i < nLength; i++)
                    {
                      result->snapshotItem(i);
                      theSerializer->write(result->getNodeValue(), theOutputDesc);
                    }

                    result->release();
                    resolver->release ();
                }
                catch(const DOMXPathException& e)
                {
                    XERCES_STD_QUALIFIER cerr << "An error occurred during processing of the XPath expression. Msg is:"
                        << XERCES_STD_QUALIFIER endl
                        << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
                    retval = 4;
                }
                catch(const DOMException& e)
                {
                    XERCES_STD_QUALIFIER cerr << "An error occurred during processing of the XPath expression. Msg is:"
                        << XERCES_STD_QUALIFIER endl
                        << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
                    retval = 4;
                }
                XMLString::release(&xpathStr);
            }
            else
                theSerializer->write(doc, theOutputDesc);

            theOutputDesc->release();
            theSerializer->release();

            //
            // Filter, formatTarget and error handler
            // are NOT owned by the serializer.
            //
            delete myFormTarget;
            delete myErrorHandler;

            if (gUseFilter)
                delete myFilter;

        }
        catch (const OutOfMemoryException&)
        {
            XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
            retval = 5;
        }
        catch (XMLException& e)
        {
            XERCES_STD_QUALIFIER cerr << "An error occurred during creation of output transcoder. Msg is:"
                << XERCES_STD_QUALIFIER endl
                << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
            retval = 4;
        }

    }
    else
        retval = 4;

    //
    //  Clean up the error handler. The parser does not adopt handlers
    //  since they could be many objects or one object installed for multiple
    //  handlers.
    //
    delete errReporter;

    //
    //  Delete the parser itself.  Must be done prior to calling Terminate, below.
    //
    delete parser;

    XMLString::release(&gOutputEncoding);

    // And call the termination method
    XMLPlatformUtils::Terminate();

    return retval;
}
Beispiel #10
0
void CTibiaItem::saveItemLists()
{
	if (!xmlInitialised)
	{
		XMLPlatformUtils::Initialize();
		xmlInitialised = 1;
	}

	char installPath[1024]       = { '\0' };
	unsigned long installPathLen = 1023;
	HKEY hkey                    = NULL;
	if (!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Tibia Auto\\", 0, KEY_READ, &hkey))
	{
		RegQueryValueEx(hkey, TEXT("Install_Dir"), NULL, NULL, (unsigned char *)installPath, &installPathLen);
		RegCloseKey(hkey);
	}
	if (!strlen(installPath))
	{
		AfxMessageBox("ERROR! Unable to read TA install directory! Please reinstall!");
		PostQuitMessage(-1);
		return;
	}
	XercesDOMParser *parser = new XercesDOMParser();
	try
	{
		//int itemNr;
		char pathBuf[2048];
		sprintf(pathBuf, "%s\\data\\tibiaauto-items.xml", installPath);

		DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(XMLString::transcode("Core"));

		xercesc::DOMDocument *doc = impl->createDocument(0, XMLString::transcode("item-definitions"), 0);
		doc->createComment((const unsigned short *)"<!-- Tibia Items for Tibia -->");

		DOMElement *root = doc->getDocumentElement();

		//ITEMS
		DOMNode *itemsNode = doc->createElement(XMLString::transcode("items"));
		root->appendChild(itemsNode);
		//recursively save data structure to XML
		saveItemsBranch(itemsNode, itemTree, doc);

		//FOOD
		DOMNode *foodNode = doc->createElement(XMLString::transcode("foods"));
		root->appendChild(foodNode);
		{
			int size = foodList.GetCount();
			for (int i = 0; i < size; i++)
			{
				char buf[512];
				DOMElement*  itemElem = doc->createElement(XMLString::transcode("item"));
				foodNode->appendChild(itemElem);
				char* name = foodList.GetTextAtIndex(i);
				int id     = foodList.GetValueAtIndex(i);
				int time   = foodList.GetExtraInfoAtIndex(i);

				sprintf(buf, "0x%x", id);
				itemElem->setAttribute(XMLString::transcode("id"), XMLString::transcode(buf));

				itemElem->setAttribute(XMLString::transcode("name"), XMLString::transcode(name));

				sprintf(buf, "%d", time);
				itemElem->setAttribute(XMLString::transcode("time"), XMLString::transcode(buf));
			}
		}
		//CONSTS
		/* never any need to save constants anymore
		   DOMNode *constsNode = doc->createElement(XMLString::transcode("consts"));
		   root->appendChild(constsNode);
		   int size = constCodeList.GetCount();
		   for (int i=0;i<size;i++){
		   char buf[512];
		   DOMElement*  itemElem = doc->createElement(XMLString::transcode("const"));
		   constsNode->appendChild(itemElem);
		   char* code=constCodeList.GetTextAtIndex(i);
		   int value=constCodeList.GetValueAtIndex(i);

		   sprintf(buf, "0x%x", value);
		   itemElem->setAttribute(XMLString::transcode("value"), XMLString::transcode(buf));

		   itemElem->setAttribute(XMLString::transcode("code"), XMLString::transcode(code));
		   }
		 */

		XMLCh tempStr[100];
		XMLString::transcode("LS", tempStr, 99);

		impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
		DOMLSSerializer* theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
		DOMConfiguration* dc           = theSerializer->getDomConfig();
		if (dc->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
			dc->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);
		XMLFormatTarget *outFile = new LocalFileFormatTarget(pathBuf);
		DOMLSOutput *lsOut       = ((DOMImplementationLS*)impl)->createLSOutput();
		lsOut->setByteStream(outFile);
		theSerializer->write(doc, lsOut);
		theSerializer->release();
		lsOut->release();
		delete outFile;
	}
	catch (...)
	{
		AfxMessageBox("Unable to save item definitions!");
	}

	delete parser;
}
Beispiel #11
0
int main(int argC, char*argV[])
{
        // Initialize the XML4C2 system.
        try
        {
                XMLPlatformUtils::Initialize();/*init*/
        }
        catch(const XMLException& toCatch)
        {
                char *pMsg = XMLString::transcode(toCatch.getMessage());
                XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n"
                        << "  Exception message:"
                        << pMsg;
                XMLString::release(&pMsg);
                return 1;
        }

        DOMImplementation* impl =  DOMImplementationRegistry::getDOMImplementation(X("LS"));/**Implementation*/
        DOMLSSerializer*   theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();/** createLSSerializer*/
        DOMLSOutput       *theOutputDesc = ((DOMImplementationLS*)impl)->createLSOutput();/**createLSOutput*/
        MemBufFormatTarget* target = new MemBufFormatTarget();
        theOutputDesc->setByteStream(target);

        if (impl != NULL)
        {
                try
                {
                        DOMDocument* doc = impl->createDocument(
                                        0,                    // root element namespace URI. /**可用资源标识*/
                                        X("corporation"),     // root element name /**a large companny*/
                                        0);                   // document type object (DTD). /**mem mannager mode object*/
                        doc->setXmlStandalone(true);

                        DOMElement*  rootElem = doc->getDocumentElement();
                        rootElem->setAttribute(X("xmlns"), X("com:cmcc:corporation"));
                        rootElem->setAttribute(X("xmlns:xsi"), X("http://www.w3.org/2001/XMLSchema-instance"));
                        rootElem->setAttribute(X("xsi:schemaLocation"), X("com:cmcc:corporation corporation.xsd"));

                        //add node
                        DOMElement*  prodElem = doc->createElement(X("eid"));
                        rootElem->appendChild(prodElem);

                        DOMText* prodDataVal = doc->createTextNode(X("100000"));
                        prodElem->appendChild(prodDataVal);

                        XercesDOMParser* parser = new XercesDOMParser();

                        //add basic child
                        MemBufInputSource* basic_mem = new MemBufInputSource(
                                        (const XMLByte* )basic_string.c_str(),
                                        strlen(basic_string.c_str()),
                                        "basic",
                                        false);
                        parser->parse( *basic_mem );
                        DOMDocument* xmlDoc = parser->getDocument();
                        DOMElement* basic_root = xmlDoc->getDocumentElement();
                        DOMNode* newnode = doc->importNode((DOMNode* )basic_root, true);
                        rootElem->appendChild(newnode); 
                        delete basic_mem;

                        //add the rules child
                        MemBufInputSource* rules_mem = new MemBufInputSource(
                                        (const XMLByte* )rules_string.c_str(),
                                        rules_string.length(),
                                        "rules",
                                        false);
                        parser->parse( *rules_mem );
                        xmlDoc = parser->getDocument();
                        DOMElement* rules_root = xmlDoc->getDocumentElement();
                        newnode = doc->importNode((DOMNode* )rules_root, true);
                        rootElem->appendChild(newnode);
                        delete rules_mem;

                        //add the accounts child
                        MemBufInputSource* accounts_mem = new MemBufInputSource(
                                        (const XMLByte* )accounts_string.c_str(),
                                        accounts_string.length(),
                                        "accounts",
                                        false);
                        parser->parse( *accounts_mem );
                        xmlDoc = parser->getDocument();
                        DOMElement* accounts_root = xmlDoc->getDocumentElement();
                        newnode = doc->importNode((DOMNode* )accounts_root, true);
                        rootElem->appendChild(newnode);
                        delete accounts_mem;

                        theSerializer->write(doc, theOutputDesc);
                        std::cout<< target->getRawBuffer()<< std::endl;

                        delete target;
                        delete parser;
                        theOutputDesc->release();
                        theSerializer->release();
                        doc->release();
                }
                catch(const OutOfMemoryException&)
                {
                        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
                }
                catch (const DOMException& e)
                {
                        XERCES_STD_QUALIFIER cerr << "DOMException code is:  " << e.code << XERCES_STD_QUALIFIER endl;
                }
                catch (...)
                {
                        XERCES_STD_QUALIFIER cerr << "An error occurred creating the document" << XERCES_STD_QUALIFIER endl;
                }
        }
        else
        {
                XERCES_STD_QUALIFIER cerr << "Requested implementation is not supported" << XERCES_STD_QUALIFIER endl;
        }

        XMLPlatformUtils::Terminate();
        return 0;
}