示例#1
0
void serializer::serialize(EObject_ptr obj)
{
    m_root_obj = obj;

    m_impl = DOMImplementationRegistry::getDOMImplementation(X("Core"));

    if (m_impl)
    {
        EClass_ptr cl = obj->eClass();
        EPackage_ptr pkg = cl->getEPackage();

        ::ecorecpp::mapping::type_traits::string_t const& ns_uri = pkg->getNsURI();

        m_doc = m_impl->createDocument(
                (ns_uri.empty()) ? X("NULL") : W(ns_uri), // root element namespace URI.
                W(get_type(obj)), // root element name
                0); // document type object (DTD)

        m_root = m_doc->getDocumentElement();

        // common attributes
        // xmlns:xmi="http://www.omg.org/XMI"
        m_root->setAttribute(X("xmlns:xmi"), X("http://www.omg.org/XMI"));
        // xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        m_root->setAttribute(X("xmlns:xsi"),
                X("http://www.w3.org/2001/XMLSchema-instance"));
        // xmi:version="2.0"
        m_root->setAttribute(X("xmi:version"), X("2.0"));

        serialize_node(m_root, obj);

        // write
        // TODO: outta here

        DOMLSSerializer *theSerializer =
                ((DOMImplementationLS*) m_impl)->createLSSerializer();
        DOMLSOutput *theOutputDesc =
                ((DOMImplementationLS*) m_impl)->createLSOutput();

        DOMConfiguration* serializerConfig = theSerializer->getDomConfig();

        // TODO: set as option
        if (serializerConfig->canSetParameter(
                XMLUni::fgDOMWRTFormatPrettyPrint, true))
            serializerConfig->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint,
                    true);

        XMLFormatTarget *myFormTarget;
        myFormTarget = new LocalFileFormatTarget(X(m_file));
        theOutputDesc->setByteStream(myFormTarget);

        theSerializer->write(m_doc, theOutputDesc);

        theOutputDesc->release();
        theSerializer->release();
        delete myFormTarget;
    }
    else
        throw "Error";
}
/* Write the file. */
bool GQCFileData::Write(const std::string &fileName)
{    
	// Initialize the XML4C2 system.
	try
	{
		XMLPlatformUtils::Initialize();
	}
	catch (const XMLException&)
	{
		return false;
	}

	// Create a DOM implementation object and create the document type for it.
	DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(ToXMLCh(L"LS"));
	DOMDocument* doc = impl->createDocument();
	//doc->setStandalone(true);

	// Create the serializer.
	DOMLSSerializer *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
	DOMLSOutput     *theOutputDesc = ((DOMImplementationLS*)impl)->createLSOutput();
	//theSerializer->setEncoding(ToXMLCh(GENERIC_REPORT_FILE_ENCODING));
	theOutputDesc->setEncoding(ToXMLCh(GENERIC_REPORT_FILE_ENCODING));

    // Create the root element
    DOMElement *rootElement = CreateGenericReportElement(doc);

	// store the parameters
	AddNameValuePairs(ANALYSIS_PARAMETERS, analysisParameters, doc, rootElement);
	AddNameValuePairs(QC_RESULTS, qcResults, doc, rootElement);
	AddNameValuePairs(SAMPLE_SIGNATURE, sampleSignature, doc, rootElement);

    // Add an empty table (required by the DTD)
    AddBlankReportTable(doc, rootElement);

    // Store the element to the document.
    doc->appendChild(rootElement);

	// Write the file.
	bool status = false;
	XMLFormatTarget *myFormTarget = new LocalFileFormatTarget(fileName.c_str());
	theOutputDesc->setByteStream(myFormTarget);
	try
	{
		theSerializer->write(doc, theOutputDesc);
		status = true;
	}
	catch (...)
	{
		status = false;
	}

	// Clean up
	doc->release();
	theOutputDesc->release();
	theSerializer->release();
	delete myFormTarget;
	XMLPlatformUtils::Terminate();

	return status;
}
示例#3
0
void SerializeXercesDocument(xercesc::DOMDocument& document, xercesc::XMLFormatTarget& target) {

	// call into xerces for serialization
	// cf. http://xerces.apache.org/xerces-c/program-dom-3.html#DOMLSSerializer

	static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };
	DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(gLS);

	// construct the DOMWriter
	DOMLSSerializer *writer = ((DOMImplementationLS*)impl)->createLSSerializer();

    // optionally you can set some features on this serializer
    if (writer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true))
        writer->getDomConfig()->setParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true);

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

	// prepare output
	DOMLSOutput *outp = ((DOMImplementationLS*)impl)->createLSOutput();
	outp->setByteStream(&target);

	// serialize the DOMNode to a UTF-16 string
	writer->write(&document, outp);

	// release the memory
	outp->release();
	writer->release();

}
//
// domPrint  -  Dump the contents of a DOM node.
//              For debugging failures, when all else fails.
//                 Works recursively - initially called with a document node.
//
void ThreadParser::domPrint()
{
    printf("Begin DOMPrint ...\n");
    if (gRunInfo.dom)
    {
        try
        {
            XMLCh tempStr[100];
            XMLString::transcode("LS", tempStr, 99);
            DOMImplementation *impl          = DOMImplementationRegistry::getDOMImplementation(tempStr);
            DOMLSSerializer   *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
            DOMLSOutput       *theOutput     = ((DOMImplementationLS*)impl)->createLSOutput();
            XMLFormatTarget   *myFormTarget  = new StdOutFormatTarget();
            theOutput->setByteStream(myFormTarget);
            DOMNode           *doc           = fXercesDOMParser->getDocument();
            theSerializer->write(doc,theOutput);
            delete myFormTarget;
            theSerializer->release();
            theOutput->release();
        }
        catch (...)
        {
            // do nothing
        }
    }
    printf("End DOMPrint\n");
}
示例#5
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.");
 }
示例#6
0
void Normalizer::serializeNode(const DOMNode * const node) {
    XMLCh tempStr[100];
    XMLString::transcode("LS", tempStr, 99);
    DOMImplementation *impl          = DOMImplementationRegistry::getDOMImplementation(tempStr);
    DOMLSSerializer   *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
    DOMLSOutput       *theOutput     = ((DOMImplementationLS*)impl)->createLSOutput();
    theSerializer->getDomConfig()->setParameter(X("format-pretty-print"), true);
    XMLFormatTarget *myFormTarget;
    myFormTarget = new StdOutFormatTarget();

    theOutput->setByteStream(myFormTarget);
    theSerializer->write(node,theOutput);
    delete myFormTarget;
    theSerializer->release();
    theOutput->release();
}
示例#7
0
Triggerconf::~Triggerconf ()
{
	if( savechanges ){
	
		//
		// save file
		//
	
		static const XMLCh	gLS []	= {chLatin_L, chLatin_S, chNull};
		DOMImplementation*	impl	= DOMImplementationRegistry::getDOMImplementation(gLS);
		DOMLSSerializer*	writer	= ((DOMImplementationLS*)impl)->createLSSerializer();
	
		if (writer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
			writer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);
	
		if (writer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTBOM, true))
			writer->getDomConfig()->setParameter(XMLUni::fgDOMWRTBOM, true);
	
		XMLFormatTarget* target	= new LocalFileFormatTarget (file.c_str ());
		target->flush();
	
		DOMLSOutput* output = ((DOMImplementationLS*)impl)->createLSOutput();
		output->setByteStream( target );
		writer->write( rootnode , output );
		
		writer->release();
		delete target;
		delete output;

	} // if( savechanges )

	//
	// delete all stuff here
	//

	delete parser;
	delete errhandler;

	//
	// now we can safely terminate xerces
	//

	XMLPlatformUtils::Terminate();
}
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;
}
示例#9
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;
}
示例#10
0
文件: xml_utils.cpp 项目: 8l/insieme
string XmlUtil::convertDomToString() {
    if(!doc)
        throw "DOM is empty"; // FIXME add an exception type for this

    DOMImplementationLS* implLS = dynamic_cast<DOMImplementationLS*>(impl);
    DOMLSSerializer*	theSerializer = implLS->createLSSerializer();
    DOMConfiguration* 	serializerConfig = theSerializer->getDomConfig();

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

    string stringTemp = XMLString::transcode (theSerializer->writeToString(doc));
    theSerializer->release();

    /*string stringDump;
    for (string::iterator it = stringTemp.begin() ; it < stringTemp.end(); ++it) {
    	if (!isspace (*it))
    		stringDump += *it;
    }
    return stringDump;*/
    return stringTemp;
}
示例#11
0
void Deployment_Plan_Visitor::write_document (const std::string & basename)
{
  std::ostringstream filename;
  filename << this->config_.output_ << "\\" << basename << ".cdp";

  using namespace xercesc;

  // Write the XML document to a file.
  DOMLSSerializer * serializer = this->document_->impl ()->createLSSerializer ();

  if (serializer->getDomConfig ()->canSetParameter (XMLUni::fgDOMWRTDiscardDefaultContent, true))
    serializer->getDomConfig ()->setParameter (XMLUni::fgDOMWRTDiscardDefaultContent, true);

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

  if (serializer->getDomConfig ()->canSetParameter (XMLUni::fgDOMWRTBOM, false))
    serializer->getDomConfig ()->setParameter (XMLUni::fgDOMWRTBOM, false);

  serializer->writeToURI (this->document_->root (), GAME::Xml::String (filename.str ()));
  serializer->release ();
}
示例#12
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();
}
示例#13
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(); 
} 
示例#14
0
bool ClsDataClientConfigWriter::saveConfig(string strFileName, list<ClsDataClientConfig> lstConfigs) {
//    cout << "ClsDataClientConfigWriter::saveConfig(string strFileName, list<ClsDataClientConfig> lstConfigs)" << endl;

    if(!bXMLPlatformInitialized){
	try {
	    XMLPlatformUtils::Initialize();
	}
	catch(const XMLException& toCatch) {
	    cerr << "Error during Xerces-c Initialization.\n"
		 << "  Exception message:"
		 << toCatch.getMessage() << endl;
	    bXMLPlatformInitialized = false;
	    return false;
	}
	bXMLPlatformInitialized = true;
    }


    DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(XMLString::transcode((const char*)"Range"));

    DOMDocumentType *dtd = impl->createDocumentType(XMLString::transcode(ConfigTagLibrary::DataManagerConfiguration()),
						    XMLString::transcode("-//INI/iqr421"),
						    XMLString::transcode("iqrDataManagerConfiguration.dtd"));

    DOMDocument *ddocConfig = impl->createDocument(0, XMLString::transcode(ConfigTagLibrary::DataManagerConfiguration()), dtd);

    DOMElement *delemConfig;
    delemConfig = ddocConfig->getDocumentElement();

    list<ClsDataClientConfig>::iterator itConfigs;
    for(itConfigs=lstConfigs.begin(); itConfigs != lstConfigs.end(); itConfigs++){
	string strID = (*itConfigs).getID();
	string strType =  (*itConfigs).getType();
	pair<int,int> pPosition =  (*itConfigs).getPosition();
	pair<int,int> pGeometry =  (*itConfigs).getGeometry();

 	DOMElement *delemDataClient;
	delemDataClient = ddocConfig->createElement(XMLString::transcode(ConfigTagLibrary::DataClientTag()));
	delemDataClient->setAttribute(XMLString::transcode(ConfigTagLibrary::TypeTag()), XMLString::transcode(strType.c_str()));
	delemDataClient->setAttribute(XMLString::transcode(ConfigTagLibrary::IDTag()), XMLString::transcode(strID.c_str()));
	delemConfig->appendChild(delemDataClient);

 	DOMElement *delemPosition;
	delemPosition = ddocConfig->createElement(XMLString::transcode(ConfigTagLibrary::PositionTag()));
	delemPosition->setAttribute(XMLString::transcode(ConfigTagLibrary::PositionXTag()), 
				    XMLString::transcode(iqrUtils::int2string(pPosition.first).c_str()));
	delemPosition->setAttribute(XMLString::transcode(ConfigTagLibrary::PositionYTag()),
				    XMLString::transcode(iqrUtils::int2string(pPosition.second).c_str()));
	delemDataClient->appendChild(delemPosition);

 	DOMElement *delemGeometry;
	delemGeometry = ddocConfig->createElement(XMLString::transcode(ConfigTagLibrary::Geometry()));
	delemGeometry->setAttribute(XMLString::transcode(ConfigTagLibrary::GeometryWidthTag()), 
				    XMLString::transcode(iqrUtils::int2string(pGeometry.first).c_str()));
	delemGeometry->setAttribute(XMLString::transcode(ConfigTagLibrary::GeometryHeightTag()), 
				    XMLString::transcode(iqrUtils::int2string(pGeometry.second).c_str()));
	delemDataClient->appendChild(delemGeometry);



	list<pair<string, string> > lstParameters = (*itConfigs).getListParameters();
	list<pair<string, string> >::iterator itLstParameters;
	for(itLstParameters = lstParameters.begin(); itLstParameters != lstParameters.end(); itLstParameters++){
	    string strParamName = (*itLstParameters).first;
	    string strParamValue = (*itLstParameters).second;
	    DOMElement *delemParameter;
	    delemParameter = ddocConfig->createElement(XMLString::transcode(strParamName.c_str()));
	    delemDataClient->appendChild(delemParameter);
	    DOMText *dtxtParamValue = ddocConfig->createTextNode(XMLString::transcode(strParamValue.c_str()));
	    delemParameter->appendChild(dtxtParamValue);
	}

 	DOMElement *delemSVD;
	delemSVD = ddocConfig->createElement(XMLString::transcode(ConfigTagLibrary::StateVariableDisplayTag()));
	delemDataClient->appendChild(delemSVD);

	list<ClsStateVariableDisplayConfig>lstSVDConfigs =  (*itConfigs).getListStateVariableDisplayConfig();
	list<ClsStateVariableDisplayConfig>::iterator itSVD;
	for(itSVD = lstSVDConfigs.begin(); itSVD != lstSVDConfigs.end(); itSVD++){
	    DOMElement *delemStateVariable;
	    delemStateVariable = ddocConfig->createElement(XMLString::transcode(ConfigTagLibrary::StateVariableDisplaysTag()));
	    delemSVD->appendChild(delemStateVariable);
	    delemStateVariable->setAttribute(XMLString::transcode(ConfigTagLibrary::IDTag()), 
					     XMLString::transcode((*itSVD).getID().c_str()));
	    
/*
	    delemStateVariable->setAttribute(XMLString::transcode(ConfigTagLibrary::TypeTag()), 
					     XMLString::transcode((*itSVD).getItemType().c_str()));
*/
	
	    delemStateVariable->setAttribute(XMLString::transcode(ConfigTagLibrary::ItemIDTag()), 
					     XMLString::transcode((*itSVD).getItemID().c_str()));

	    delemStateVariable->setAttribute(XMLString::transcode(ConfigTagLibrary::SelectedIndicesTag()), 
					     XMLString::transcode((*itSVD).getSelectedIndices().c_str()));

	    list<pair<string, string> > lstParametersSVD = (*itSVD).getListParameters();
	    list<pair<string, string> >::iterator itLstParametersSVD;
	    for(itLstParametersSVD = lstParametersSVD.begin(); itLstParametersSVD != lstParametersSVD.end(); itLstParametersSVD++){
		string strParamName = (*itLstParametersSVD).first;
		string strParamValue = (*itLstParametersSVD).second;
		DOMElement *delemParameter;
		delemParameter = ddocConfig->createElement(XMLString::transcode(strParamName.c_str()));
		delemStateVariable->appendChild(delemParameter);
		DOMText *dtxtParamValue = ddocConfig->createTextNode(XMLString::transcode(strParamValue.c_str()));
		delemParameter->appendChild(dtxtParamValue);
	    }
	}
    }


#if XERCES_VERSION_MAJOR >= 3
    DOMLSSerializer* theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
    if (theSerializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true))
	theSerializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true);

    if (theSerializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
	theSerializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);
#else
    DOMWriter* theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter();
    if (theSerializer->canSetFeature(XMLUni::fgDOMWRTDiscardDefaultContent, true))
	theSerializer->setFeature(XMLUni::fgDOMWRTDiscardDefaultContent, true);

    if (theSerializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true))
	theSerializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true);
#endif

    XMLFormatTarget *myFormTarget = new LocalFileFormatTarget(strFileName.c_str());

#if XERCES_VERSION_MAJOR >= 3
    DOMLSOutput* theOutput = ((DOMImplementationLS*)impl)->createLSOutput();
    theOutput->setByteStream(myFormTarget);
#endif


    try {
#if XERCES_VERSION_MAJOR >= 3
	theSerializer->write(delemConfig, theOutput);
#else
	theSerializer->writeNode(myFormTarget, *delemConfig);
#endif
    }
    catch (const XMLException& toCatch) {
	char* message = XMLString::transcode(toCatch.getMessage());
	cerr << "Exception message is: \n"
	     << message << "\n";
	XMLString::release(&message);
    }
    catch (const DOMException& toCatch) {
	char* message = XMLString::transcode(toCatch.msg);
	cerr << "Exception message is: \n"
	     << message << "\n";
	XMLString::release(&message);
    }
    catch (...) {
	cerr << "Unexpected Exception \n" ;
    }

//    cout << myFormTarget->getRawBuffer() << endl;

    theSerializer->release();
    delete myFormTarget;


    return true;

}
示例#15
0
Triggerconf::Triggerconf(string _filename, bool _autocreateitems, bool _mustexist, bool _savechanges)
	: file( _filename ), autocreate( _autocreateitems ), savechanges( _savechanges ) {

	rootnode	= NULL;
	goodstate	= true;
	lasterror	= "";
    
	try {

		XMLPlatformUtils::Initialize();

		//
		// if the file does not exists we create it with the root node
		// but only if the constructor parameter is fine with this
		//

		FileHandle filehandle = XMLPlatformUtils::openFile (file.c_str ());
		
		if (filehandle == NULL && _mustexist == false) {

			static const XMLCh	gLS []	= {chLatin_L, chLatin_S, chNull};
			DOMImplementation*	impl	= DOMImplementationRegistry::getDOMImplementation(gLS);
			
			XMLCh*			xroot	= XMLString::transcode( ROOT_NAME );
			DOMDocument*		doc	= impl->createDocument( 0, xroot, 0 );
			DOMElement*		elemrt	= doc->getDocumentElement();
			DOMLSSerializer* 	writer  = ((DOMImplementationLS*)impl)->createLSSerializer();
			
			XMLString::release (&xroot);

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

			if (writer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTBOM, true))
				writer->getDomConfig()->setParameter(XMLUni::fgDOMWRTBOM, true);

			XMLFormatTarget* target	= new LocalFileFormatTarget (file.c_str ());
			target->flush();

			DOMLSOutput* output = ((DOMImplementationLS*)impl)->createLSOutput();
        		output->setByteStream( target );
            		writer->write( elemrt, output );

			writer->release();
			doc->release();

			delete output;
			delete target;

		} else if (filehandle == NULL && _mustexist == true) {

			setError ("file " + file + " does not exist");
			return;

		} else {

			XMLPlatformUtils::closeFile (filehandle);

		}

		//
		// parse the file
		//

		parser		= new XercesDOMParser ();
		errhandler	= (ErrorHandler*) new HandlerBase ();

		parser->setErrorHandler	(errhandler);
		parser->parse		(file.c_str ());
		rootnode		= getChildOfType (parser->getDocument (), DOMNode::ELEMENT_NODE);

		if (rootnode != NULL) {
		
			char* xmlstring = XMLString::transcode (rootnode->getNodeName ());

			if (((string) ROOT_NAME).compare (xmlstring) == 0)
				resetError();
			else
				setError("invalid root item in file " + file);
		
			XMLString::release (&xmlstring);

		} else
			setError("parsing xml file " + file + " failed");	

	} catch (const XMLException& toCatch) {
		char* message = XMLString::transcode (toCatch.getMessage());
		setError ("failed parsing file " + file + ": " + message);
		XMLString::release(&message);
	}
	catch (const DOMException& toCatch) {
		char* message = XMLString::transcode (toCatch.msg);
		setError ("failed parsing file " + file + ": " + message);
		XMLString::release(&message);
	}
	catch (...) {
		setError( "failed parsing file " + file );
	}

}
示例#16
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;
}
示例#17
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;
}
示例#18
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;
}
示例#19
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;
}
示例#20
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;
}