利用DOM生成XML文档

// XMLWriter.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/dom/DOM.hpp>

#include <xercesc/framework/StdOutFormatTarget.hpp>
#include <xercesc/framework/LocalFileFormatTarget.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/util/XMLUni.hpp>

#include <..\\samples\\src\\DOMPrint\\DOMTreeErrorReporter.hpp>
//#include <DOMPrintFilter.hpp>
#include <..\\samples\\src\\DOMPrint\\DOMPrintErrorHandler.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>

#include <string.h>
#include <stdlib.h>
#include <xercesc/util/XMLString.hpp>
#include <stdio.h>
#if defined(XERCES_NEW_IOSTREAMS)
#include <iostream>
#else 
#include <iostream.h>
#endif

#pragma comment(lib, "xerces-c_3D")
XERCES_CPP_NAMESPACE_USE

// ---------------------------------------------------------------------------
//  This is a simple class that lets us do easy (though not terribly efficient)
//  trancoding of char* data to XMLCh data.
// ---------------------------------------------------------------------------
class XStr
{
public :
	// -----------------------------------------------------------------------
	//  Constructors and Destructor
	// -----------------------------------------------------------------------
	XStr(const char* const toTranscode)
	{
		// Call the private transcoding method
		fUnicodeForm = XMLString::transcode(toTranscode);
	}

	~XStr()
	{
		XMLString::release(&fUnicodeForm);
	}

	// -----------------------------------------------------------------------
	//  Getter methods
	// -----------------------------------------------------------------------
	const XMLCh* unicodeForm() const
	{
		return fUnicodeForm;
	}

private :
	// -----------------------------------------------------------------------
	//  Private data members
	//
	//  fUnicodeForm
	//      This is the Unicode XMLCh format of the string.
	// -----------------------------------------------------------------------
	XMLCh*   fUnicodeForm;
};

#define X(str) XStr(str).unicodeForm()
static char* goutputfile = "d:\\ok.xml";
void WriteXML(DOMDocument *doc, int &retval );
int _tmain(int argc, _TCHAR* argv[])
{    // Initialize the XML4C2 system.
	int errorCode = 0;	
	try
	{
		XMLPlatformUtils::Initialize();
	}

	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;
	}
	{
		//  Nest entire test in an inner block.
		//  The tree we create below is the same that the XercesDOMParser would
		//  have created, except that no whitespace text nodes would be created.

		// <company>
		//     <product>Xerces-C</product>
		//     <category idea='great'>XML Parsing Tools</category>
		//     <developedBy>Apache Software Foundation</developedBy>
		// </company>

		DOMImplementation* impl =  DOMImplementationRegistry::getDOMImplementation(X("Core"));//

		if (impl != NULL)
		{
			try
			{
				DOMDocument* doc = impl->createDocument(
					0,                    // root element namespace URI.
					X("company"),         // root element name
					0);                   // document type object (DTD).
				/*doc->*/
				DOMElement* rootElem = doc->getDocumentElement();

				DOMElement*  prodElem = doc->createElement(X("product"));
				rootElem->appendChild(prodElem);

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

				DOMElement*  catElem = doc->createElement(X("category"));
				rootElem->appendChild(catElem);

				catElem->setAttribute(X("idea"), X("great"));
				catElem->setAttribute(X("xuehao"), X("123"));

				DOMText*    catDataVal = doc->createTextNode(X("XML Parsing Tools"));
				catElem->appendChild(catDataVal);

				DOMElement*  devByElem = doc->createElement(X("developedBy"));
				rootElem->appendChild(devByElem);

				DOMText*    devByDataVal = doc->createTextNode(X("Apache Software Foundation"));
				devByElem->appendChild(devByDataVal);

				//
				// Now count the number of elements in the above DOM tree.
				//

				const XMLSize_t elementCount = doc->getElementsByTagName(X("*"))->getLength();//
				XERCES_STD_QUALIFIER cout << "The tree just created contains: " << elementCount
					<< " elements." << XERCES_STD_QUALIFIER endl;
				int ret = 0;
				WriteXML(doc,ret);
				doc->release();
			}
			catch (const OutOfMemoryException&)
			{
				XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
				errorCode = 5;
			}
			catch (const DOMException& e)
			{
				XERCES_STD_QUALIFIER cerr << "DOMException code is:  " << e.code << XERCES_STD_QUALIFIER endl;
				errorCode = 2;
			}
			catch (...)
			{
				XERCES_STD_QUALIFIER cerr << "An error occurred creating the document" << XERCES_STD_QUALIFIER endl;
				errorCode = 3;
			}
		}  // (inpl != NULL)
		else
		{
			XERCES_STD_QUALIFIER cerr << "Requested implementation is not supported" << XERCES_STD_QUALIFIER endl;
			errorCode = 4;
		}
	}

	XMLPlatformUtils::Terminate();
	return errorCode;
}

void WriteXML(/* DOMPrintFilter * &myFilter, XercesDOMParser * parser,*/DOMDocument *doc, int &retval ) 
{
	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;
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值