Source: queryNodesSmart.cpp
This example application calls both the selectSingleNode
method and the selectNodes
method on an XML DOM object loaded from the stocks.xml file. The same XPath expression is input to both methods:
//stock[1]/*
This expression specifies all the child elements of the first <stock>
element in the XML document. In MSXML, the selectSingleNode
method returns the first element of the resultant node-set, and the selectNodes
method returns all the elements in the node-set.
Programmatically, this source code performs the following steps:
- Creates an instance of an XML DOM object (
pXMLDom
). - Calls the
load
method onpXMLDom
to load XML data from a file (stocks.xml). - Calls the
selectSingleNode
method onpXMLDom
to select a DOM node according to the input XPath expression (//stock[1]/*
). Then displays the resulting node in the console if the query is successful. - Calls the
selectNodes
method onpXMLDom
to select a DOM node-set according to the input XPath expression ("//stock[1]/*
"). Then displays the resulting nodes in the console if the query is successful.
C/C++ Source File (queryNodesSmart.cpp)
#include <stdio.h> #import <msxml5.dll> using namespace MSXML2; int main(int argc, char* argv[]) { IXMLDOMDocument3Ptr pXMLDom; HRESULT hr; CoInitialize(NULL); hr = pXMLDom.CreateInstance(__uuidof(DOMDocument50)); if (FAILED(hr)) { printf("Failed to instantiate DOMDocument50 class\n"); return -1; } pXMLDom->async = VARIANT_FALSE; if ( pXMLDom->load("stocks.xml") != VARIANT_TRUE) { printf("Failed load xml data from file.\n%s\n", (LPCSTR)pXMLDom->parseError->Getreason()); return -1; } // Query a single node. IXMLDOMNodePtr pNode = pXMLDom->selectSingleNode("//stock[1]/*"); if (pNode == NULL) { printf("Invalid node fetched.\n%s\n", (LPCSTR)pXMLDom->parseError->Getreason()); } else { printf("Result from selectSingleNode:\nNode, <%s>:\n\t%s\n\n", (LPCSTR)pNode->nodeName, (LPCSTR)pNode->xml); } // Query a node-set. IXMLDOMNodeListPtr pnl = pXMLDom->selectNodes("//stock[1]/*"); printf("Results from selectNodes:\n"); for (int i=0; i<pnl->length; i++) { pNode = pnl->item[i]; printf("Node (%d), <%s>:\n\t%s\n", i, (LPCSTR)pNode->nodeName, (LPCSTR)pnl->item[i]->xml); } pXMLDom.Release(); pNode.Release(); pnl.Release(); CoUninitialize(); return 0; }
To add the queryNodes source code to the project
- Select FileView on the project browser, and highlight queryNodeSmartProj files. From the File menu, select New.
- On the Files tab of the New dialog box, highlight C++ Source File. Then type "queryNodes.cpp" in the File name text box, and click OK.
- Copy the C/C++ source code above and paste it into the source file you just created.
Next, we'll add the resource file to the queryNodesSmart project.