Wednesday, October 31, 2007

Use encoding to write xml using MSXML

If you want to write the xml file of different encoding using MSXL, you need to add a precessing instruction node to you xml document. Here is the code in c++ for encoding UTF-16.

// pXMLDOMDoc is the IXMLDOMDocument pointer

IXMLDOMNode* pNode = NULL;
IXMLDOMProcessingInstruction* pInstruct = NULL;

USES_CONVERSION;
BSTR value = T2BSTR(_T("version='1.0' encoding='UTF-16'"));
BSTR xml = T2BSTR(_T("xml"));

// Create the processing instruction node
HRESULT hr = pXMLDOMDoc->createProcessingInstruction( xml, value, &pInstruct);
if(SUCCEEDED(hr) && pInstruct)
{
// Append the processing instruction node to the XML document
pXMLDOMDoc->appendChild(pInstruct, &pNode);

HCOM_Release(pInstruct);
HCOM_Release(pNode);
}

SysFreeString(value);
SysFreeString(xml);

// Set the root node as reference element of the XML document
if(SUCCEEDED(hr) && pInstruct)
{
IXMLDOMElement* pRootNode = NULL;
pXMLDOMDoc->get_documentElement(&pRootNode);
if(pRootNode != NULL)
pXMLDOMDoc->putref_documentElement(pRootNode);
}


// Now save the xml
pXMLDOMDoc->save(VARIANT_FromBSTR(bstrFileName));

No comments: