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:
pXMLDom
).load
method on pXMLDom
to load XML data from a file (stocks.xml).selectSingleNode
method on pXMLDom
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.selectNodes
method on pXMLDom
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
Next, we'll add the resource file to the queryNodesSmart project.