The source code listed below demonstrates how to call the transformNode method and the transformNodeToObject method in a C/C++ program. Specifically, the code performs the following steps:
pXMLDom).pXSLDoc).transformNode(pXSLDoc) method on pXMLDom to do the transformation, holds the result in a string (xmlStr), and prints the output to the console.pXMLOut) to hold the output of the transformNodeToObject method.transformNodeToObject method on pXMLDom to do the transformation; holds the resulting object in pXMLOut; prints out the XML result; and serializes the output object in an HTML file, stocks.htm.C/C++ Source File (XSLTsmart.cpp)
#include <stdio.h>
#import <msxml5.dll>
using namespace MSXML2;
int main(int argc, char* argv[])
{
IXMLDOMDocument3Ptr pXMLDom, pXSLDoc, pXMLOut;
HRESULT hr;
CoInitialize(NULL);
// Load the XML file.
hr= pXMLDom.CreateInstance(__uuidof(DOMDocument50));
if (FAILED(hr))
{
printf("Failed to instantiate an XML DOM.\n");
return -1;
}
pXMLDom->async = VARIANT_FALSE; // The default is true.
if(pXMLDom->load("stocks.xml")!=VARIANT_TRUE)
{
printf("Failed to load stocks.xml:\n%s\n",
(LPCSTR)pXMLDom->parseError->Getreason());
return -1;
}
// Load the XSLT style sheet.
hr= pXSLDoc.CreateInstance(__uuidof(DOMDocument50));
if (FAILED(hr))
{
printf("Failed to instantiate an XML DOM.\n");
return -1;
}
pXSLDoc->async = VARIANT_FALSE; // The default is true.
if(pXSLDoc->load("stocks.xsl")!=VARIANT_TRUE)
{
printf("Failed to load stocks.xsl:\n%s\n",
(LPCSTR)pXMLDom->parseError->Getreason());
return -1;
}
// Transform the XSLT to an XML string.
_bstr_t xmlStr = pXMLDom->transformNode(pXSLDoc);
//Always remember to check for parse errors.
if(pXMLDom->parseError->errorCode != 0)
{
printf("Failed to transformNode:\n%s\n",
(LPCSTR)pXMLDom->parseError->Getreason());
}
else
{
printf("output from transformNode:\n%s\n",
(LPCSTR)xmlStr);
}
// Instantiate a DOM for xmlOut object.
hr= pXMLOut.CreateInstance(__uuidof(DOMDocument50));
if (FAILED(hr))
{
printf("Failed to instantiate an XML DOM.\n");
return -1;
}
// Transform the XSLT to a DOM object.
hr = pXMLDom->transformNodeToObject(pXSLDoc,
pXMLOut.GetInterfacePtr());
if (FAILED(hr))
{
printf("Failed to transformNodeToObject:\n%s\n",
(LPCSTR)pXMLDom->parseError->Getreason());
}
else
{
hr = pXMLOut->save("stocks.htm");
if (FAILED(hr))
{
printf("Failed to save output DOM to xslt_out.htm\n");
return -1;
}
else
{
printf("Output from transformNodeToObject:\n%s\n",
(LPCSTR)pXMLOut->xml);
printf("The above output is also saved in stocks.htm.\n");
}
}
pXMLDom.Release();
pXSLDoc.Release();
pXMLOut.Release();
CoUninitialize();
return 0;
}
To add the XSLT source code to the project
Next, we'll add the resource files to the XSLT project.