본문 바로가기

Projects/CoVNC

MSXML 사용법 요약

Summary
This sample application shows how to use MSXML 4.0 to create an XML document using DOM. This application illustrates the following DOM APIs: createProcessingInstruction, insertBefore, createNode, appendChild, createElement, createAttribute, setNamedItem, createComment, createCDATASection, createDocumentFragment, setAttribute, and save.

Our objective is to use MSXML 4.0 DOM and create the XML document that looks like as below:
<?xml version="1.0" encoding="UTF-8"?>
<f:Feedback xmlns:f='www.PerfectXML.com/Feedback'>
	<f:Record f:RecID="231">
		
		<!-- The Feedback Text -->
		<![CDATA[
	PerfectXML is now by far the best source on the Web 
	for up-to-date news on Web services and XML. Congrats!]]>

		<f:Recd>
			Thu Jul 11 2002
		</f:Recd>
		
		<f:Time>
			09:01:40
		</f:Time>

		<f:From>
			Roger
		</f:From>

		<f:Client f:Browser='IE' f:IP='123.123.123.123'/>

	</f:Record>
</f:Feedback>

Steps
Steps that we followed to create this application:
1. Start Visual C++ 6.0 and create a new Win32 Console Application project.
2. Add the following lines in the stdafx.h:
#include <TCHAR.H>
#include <stdio.h>
#include <time.h>

#import "msxml4.dll"
//      ^^^^^^^^^^^^
// If this import statement fails, you need to install MSXML 4.0 SP1 from:
//
// http://msdn.microsoft.com/downloads/sample.asp?url=/MSDN-FILES/027/001/766/msdncompositedoc.xml

#include <msxml2.h>
//       ^^^^^^^^^^
// If this include statement fails, you need to install MSXML 4.0 SP1 SDK from:
//
// http://msdn.microsoft.com/downloads/sample.asp?url=/MSDN-FILES/027/001/766/msdncompositedoc.xml
//
// You also need to add the include file and library search path
// to Visual C++'s list of directories (Tools > Options... > Directories).

using namespace MSXML2;

inline void EVAL_HR( HRESULT _hr ) 
   { if FAILED(_hr) throw(_hr); }

#define TEMP_SIZE  _MAX_PATH       // size of short buffer
static _TCHAR   szTemp[TEMP_SIZE]; // multipurpose buffer on stack
static DWORD    dwLen;
3. The above lines import the MSXML 4 type library, include the MSXML header file, defines a tiny utility function to check the HRESULT value, and declares some global variables.
4. The main function looks like as below:
int main(int argc, char* argv[])
{
	try
	{
		EVAL_HR(CoInitialize(NULL));

		//	Make sure that MSXML 4.0 is installed
		if (!isMSXMLInstalled())
			return -1;

		CreateAndSaveXMLDocument();
	}
	catch(...)
	{//exception handling
	}
	
	_ftprintf(stdout, "\n\nPress Enter to continue...");
	getchar();
	CoUninitialize();
	return 0;
}
5. The main function begins by calling the utility function isMSXMLInstalled to make sure MSXML 4.0 is installed. This function is discussed in previous two samples, so we'll not repeat the explaination here.

Next, the main function calls CreateAndSaveXMLDocument function which actually creates and saves the XML document. This function is saved in utils.h file. Let's look at this function:
6. The function begins by creating an instance of MSXML DOMDocument object:
void CreateAndSaveXMLDocument()
{
	try
	{
		IXMLDOMDocument2Ptr pXMLDoc = NULL;
		
		//	Create MSXML DOM object
		EVAL_HR(pXMLDoc.CreateInstance("Msxml2.DOMDocument.4.0"));
The first thing we do in this function is create the XML declaration line (<?xml version="1.0" encoding="UTF-8"?>)
		//	---------------------------------------------
		//	Step 6.1: Creating the Processing Instruction
		IXMLDOMProcessingInstructionPtr pPI = NULL;

		pPI = pXMLDoc->createProcessingInstruction
			("xml", "version='1.0' encoding='UTF-8'");

		_variant_t vNullVal;
		vNullVal.vt = VT_NULL;
		pXMLDoc->insertBefore(pPI, vNullVal);
The second parameter to the insertBefore function call above is passed as NULL, which instructs new node to be inserted at the end of the child list. Since we do not have any nodes in the tree yet, the XML declaration statement becomes the very first child.

Next, we create the document root element:
		//	---------------------------------------------
		//	Step 6.2: Creating the Root Element
		IXMLDOMNodePtr pRootNode= NULL; 
		_variant_t varNodeType((short)MSXML2::NODE_ELEMENT);

		pRootNode= pXMLDoc->createNode(varNodeType, 
			_T("f:Feedback"), _T("www.PerfectXML.com/Feedback"));

		pXMLDoc->appendChild(pRootNode);


The first child under the root Feedback node is the Record element:
		//	---------------------------------------------
		//	Step 6.3a: Creating Record Child Element
		IXMLDOMNodePtr pRecNode= NULL; 
		pRecNode = pRootNode->appendChild(pXMLDoc->createElement(_T("f:Record")));

		//	Step 6.3b: Creating RecID attribute for the Record element
		IXMLDOMAttributePtr pRecIdAttr = NULL;
		pRecIdAttr = pXMLDoc->createAttribute(_T("f:RecID"));
		pRecIdAttr->nodeTypedValue = _T("231");
		pRecNode->attributes->setNamedItem(pRecIdAttr);
The above lines of code create the Record element and an attribute named RecID.

The following lines of code create the comments and CDATA section:
		//	---------------------------------------------
		//	Step 6.4: Creating the Comments node
		_bstr_t bstrCommentText = _T(" The Feedback Text ");
		pRecNode->appendChild(pXMLDoc->createComment(bstrCommentText));


		//	---------------------------------------------
		//	Step 6.5: Creating the CDATA section
		_bstr_t bstrCDATAText = 
			_T("\n\tPerfectXML is now by far the best source on the Web"
				" \n\tfor up-to-date news on Web services and XML. Congrats!\n");

		pRecNode->appendChild(pXMLDoc->createCDATASection(bstrCDATAText));
The following lines of code illustrate an important concept of document fragments. Many times it is required to create and append a set of nodes at various places in the document. Instead of creating and appending each node every time, we can create a document fragment; and then just append that in the tree wherever the set of nodes is required.
		//	---------------------------------------------
		//	Step 6.6: Addding the Recd, Time, and From nodes
		//	Illustrating the document fragment feature (IXMLDOMDocumentFragment)
		IXMLDOMDocumentFragmentPtr pFragment = NULL;
		IXMLDOMElementPtr pTempNode = NULL;
		pFragment = pXMLDoc->createDocumentFragment();

		pTempNode = pXMLDoc->createElement(_T("f:Recd"));
		pTempNode->nodeTypedValue = _T("Thu Jul 11 2002");
		pFragment->appendChild(pTempNode );
		
		pTempNode = pXMLDoc->createElement(_T("f:Time"));
		pTempNode->nodeTypedValue = _T("09:01:40");
		pFragment->appendChild(pTempNode );

		pTempNode = pXMLDoc->createElement(_T("f:From"));
		pTempNode->nodeTypedValue = _T("Roger");
		pFragment->appendChild(pTempNode );

		//	Attach the fragment to the DOM tree
		pRecNode->appendChild(pFragment);
Here we are creating three nodes as part of the fragment. We can now use this fragment anywhere else also in the code to add these three nodes in the tree.

Finally, we create the Client child element and its two attributes, and then save the document:
		//	Step 6.7: Creating "Client" element and its two attributes
		IXMLDOMElementPtr pClientElem= NULL; 
		pClientElem = pXMLDoc->createElement(_T("f:Client"));
		pClientElem->setAttribute(_T("f:Browser"), _T("IE"));
		pClientElem->setAttribute(_T("f:IP"), _T("123.123.123.123"));

		pRecNode->appendChild(pClientElem);

		//	Done, now save the document

		pXMLDoc->save(_T("c:\\Feedback.xml"));
	}
	catch(...)
	{//Exception handling
	}
	
}
Here is the text from the ReadMe.TXT file included with the code download for this sample application:
==================================================
       CONSOLE APPLICATION : DOM_CreateXMLDoc
==================================================

	Sample code to illustrate using MSXML 4.0 (SP1) DOM 
	to create an XML document. This application illustrates 
	the following DOM methods: 
	createProcessingInstruction, insertBefore, createNode, appendChild,
	createElement, createAttribute, setNamedItem, createComment, 
	createCDATASection, createDocumentFragment, setAttribute, and save.

	The created document is saved as c:\Feedback.xml

--------------------------------------------------
	Copyright (C) 2002 http://www.PerfectXML.com

	Created: July 12, 2002

	Author: PerfectXML.com Team (msxml@PerfectXML.com)
---------------------------------------------------

///////////////////////////////////////////////////


More Information

'Projects > CoVNC' 카테고리의 다른 글

BSTR  (0) 2007.05.31
[Win32 API] DialogBoxParam  (0) 2007.05.20
Microsoft XML Core Service(MSXML)  (0) 2007.05.05
C++을 사용해 바이트 배열에 저장된 DIB정보를 DIB메모리 블럭 만들기  (2) 2007.03.31
DIB/DDB 구조  (0) 2007.03.30