Home > Articles

  • Print
  • + Share This
From the author of

Consuming XML



After doing COM, MSXML, and DOM housekeeping, consuming XML basically involves retrieving an element from the document (usually the Document element), and then walking the document tree and processing the different nodes encountered according to their type. A production application would have very specific processing for each node encountered, but the sample ConsumeXML.cpp program just displays the names and properties of the DOM objects encountered. (Click here for the source file.)



 1 /* ConsumeXML.cpp
 2
 3 This program illustrates basic DOM operations involved
 4 with reading an XML document using MSXML's DOM
 5 implementation.
 6
 7 Michael C. Rawlins, 2003, for InformIT
 8
 9 */
 10
 11 #include <iostream.h>
 12
 13 #import <msxml4.dll>
 14 using namespace MSXML2;
 15
 16 int main(int argc, char* argv[])
 17 {
 18
 19  // Local variables and initializations
 20  HRESULT hResult = S_OK;
 21  int i;
 22  char cNodeType;
 23
 24  cout << endl << "Sample ConsumeXML Program" << endl << endl;
 25
 26  // Initialize the COM library
 27  hResult = CoInitialize(NULL);
 28  if (FAILED(hResult))
 29  {
 30   cerr << "Failed to initialize COM environment" << endl;
 31   return 0;
 32  }
 33
 34  // Main try block for MSXML DOM operations
 35  try
 36  {
 37   // MSXML COM smart pointers
 38   // Use the Dccument2 class to enable schema validation
 39   IXMLDOMDocument2Ptr spDocInput;
 40   IXMLDOMNodePtr spNodeTemp;
 41   IXMLDOMElementPtr spElemTemp;
 42   IXMLDOMAttributePtr spAttrTemp;
 43   IXMLDOMNodeListPtr spNLChildren;
 44
 45   // Create the COM DOM Document object
 46   hResult = spDocInput.CreateInstance(__uuidof(DOMDocument40));
 47
 48   if FAILED(hResult)
 49   {
 50    cerr << "Failed to create Document instance" << endl;
 51    return 1;
 52   }
 53
 54   // Load the document synchronously
 55   spDocInput->async = VARIANT_FALSE;
 56
 57   // Load input document. MSXML default for load is to
 58   // validate while parsing.
 59   hResult = spDocInput->load("SampleDocument.xml");
 60
 61   // Check for load, parse, or validation errors
 62   if( hResult != VARIANT_TRUE)
 63   {
 64    cout << "Parsing error" << endl;
 65    return 1;
 66   }
 67
 68   // Get document element
 69   spElemTemp = spDocInput->documentElement;
 70    cout << endl
 71       << "Document Element name:  "
 72       << spElemTemp->nodeName << endl << endl;
 73
 74   // Walk through children of document element
 75   // and process according to type
 76   spNodeTemp = spElemTemp->firstChild;
 77
 78   while (spNodeTemp != NULL)
 79   {
 80    // Process node depending on type
 81    cNodeType = spNodeTemp->nodeType;
 82    switch (cNodeType)
 83    {
 84     // Comment Node
 85     case NODE_COMMENT:
 86      cout << "Comment Node:" << endl << "  "
 87         << _bstr_t(spNodeTemp->nodeValue)
 88         << endl << endl;
 89      break;
 90
 91     // Element Node
 92     case NODE_ELEMENT:
 93      spElemTemp = (IXMLDOMElementPtr) spNodeTemp;
 94      cout << "Element name:      "
 95         << spElemTemp->nodeName << endl;
 96
 97      // Display the value of Attribute1, if present
 98      // MSXML doesn't support the hasAttribute method,
 99      // so we'll try to get the Attribute node,
100      // then its value.
101      spAttrTemp =
102        spElemTemp->getAttributeNode("Attribute1");
103      if (spAttrTemp != NULL)
104      {
105       cout << "  Attribute1 Value:  "
106          << _bstr_t(spAttrTemp->nodeValue)
107          << endl;
108      }
109
110      // Process SecondLevelChild children
111      // of FirstLevelChild
112      spNLChildren =
113       spElemTemp->getElementsByTagName("SecondLevelChild");
114      for (i = 0; i < spNLChildren->length; i++)
115      {
116       spElemTemp =
117         (IXMLDOMElementPtr) spNLChildren->item[i];
118       cout << "  Element name:    "
119          << spElemTemp->nodeName << endl;
120
121       // Get the text node with the element content,
122       // and display it. If present it will be the
123       // first child.
124       IXMLDOMTextPtr spText = spElemTemp->firstChild;
125       if (spText != NULL)
126       {
127        cout << "  Element content:   "
128           << _bstr_t(spText->nodeValue) << endl;
129       }
130      }
131
132      // Finished with FirstLevelChild element
133      cout << endl;
134      break;
135
136     // Everything else allowed by the schema
137     default:
138      // Skip unexpected processing instructions
139      // and white space text nodes
140      break;
141    } // End of switch block
142
143    // Get the next child of the Document Element
144    spNodeTemp = spNodeTemp->nextSibling;
145
146   } // End of while block
147  } // End of try block
148
149  // Catch COM exceptions
150  catch (_com_error &e)
151  {
152   cerr << "COM Error" << endl;
153   cerr << "Message = " << e.ErrorMessage() << endl;
154   return 1;
155  }
156
157  // Release COM resources
158  CoUninitialize();
159
160  cout << endl << endl << "Successful Completion" << endl;
161
162  return 0;
163 }

The sample program shows two basic approaches for walking the document tree. The first approach traverses the DOM document tree from parent to child and from one sibling to the next. Lines 68–76 in the sample program initiate this approach by getting the document element SampleDocumentElement and its first child. The program then does a pre-order traversal of the document tree in the while loop from lines 78–146, using the Node interface's nextSibling property. In the second approach for walking the document tree, a specific set of nodes is retrieved by name using the getElementsByTagName method. This method retrieves a list of elements that match the name as a NodeList. This list can be traversed using various methods and properties of the NodeList interface. This is the approach is used to retrieve the SecondLevelChild children of a FirstLevelChild element, in lines 110–130. It's initiated at line 113 with the getElementsByTagName call, and proceeds with the for loop in lines 114–130, where the program steps through the items in the NodeList using the item property.

An important point to note about the MSXML DOM implementation is that the value of a DOM Node is represented as a COM VARIANT. We use the _bstr COM helper class to access the string value of an attribute at line 106 and a Text node at line 128.

As a final note, this program validates the input document against the schema, and we didn't have to do anything special to get that behavior. The default mode of operation for the load method at line 59 is to validate while parsing.

  • + Share This
  • 🔖 Save To Your Account