Microsoft XML SDK 2.6 - XML Reference

IXMLDOMElement::getElementsByTagName Method

Returns a list of all descendant elements that match the supplied name.

Visual Basic Syntax

Set objXMLDOMNodeList = oXMLDOMElement.getElementsByTagName(tagName)

C/C++ Syntax

HRESULT getElementsByTagName(
    BSTR tagName,
    IXMLDOMNodeList **resultList);

Parameters

tagName [in]
Name of the element to find. The string "*" matches all descendant elements of this element.
resultList [out]
DOMNodeList object containing all elements that match the supplied name.

C/C++ Return Values

Returns S_OK if successful, or an error code otherwise.

Remarks

Elements appear in the order encountered in a preorder traversal of this element's tree.

Note that the XMLDOMNodeList object is returned even if there are no matches. In such a case, the length of the list will be set to zero.

The IXMLDOMNodeList interface is live and immediately reflects changes to the nodes that appear in the list.

C/C++ Example

// Find all Nodes with a particular tag
BOOL DOMDocFindNodesWithTag()
{
   BOOL bResult = FALSE;
   CString strFindText (_T("AUTHOR"));
   IXMLDOMNodeList *pIDOMNodeList = NULL;
   IXMLDOMNode *pIDOMNode = NULL;
   long value = 0;
   BSTR bstrItemText = NULL;
   HRESULT hr;

   try
   {
      // Create the DOMDocument and initialise m_pIXMLDOMDocument2
      // find all "AUTHOR" elements 
      hr = m_pIXMLDOMDocument2->getElementsByTagName((TCHAR *)strFindText.GetBuffer(0), &pIDOMNodeList);
      SUCCEEDED(hr) ? 0 : throw hr;
      
      // get the length of the list returned by the previous find
      hr = pIDOMNodeList->get_length(&value);
      if(SUCCEEDED(hr))
      {
         pIDOMNodeList->reset();
      // loop through the elements found and display the contents
         for(int ii = 0; ii < value; ii++)
         {
            hr = pIDOMNodeList->get_item(ii, &pIDOMNode);
            SUCCEEDED(hr) ? 0 : throw hr;
            if(pIDOMNode)
            {
               hr = pIDOMNode->get_text(&bstrItemText);
               SUCCEEDED(hr) ? 0 : throw hr;
               if(bstrItemText)
               {
                     bResult = TRUE;
                     ::MessageBox(NULL, bstrItemText, strFindText, MB_OK);
                     ::SysFreeString(bstrItemText);
                     bstrItemText = NULL;
               }
               pIDOMNode->Release();
               pIDOMNode = NULL;
            }
         }
         pIDOMNodeList->Release();
         pIDOMNodeList = NULL;
      }
   }
   catch(...)
   {
      if(pIDOMNodeList)
         pIDOMNodeList->Release();
      if(pIDOMNode)
         pIDOMNode->Release();
      if(bstrItemText)
         ::SysFreeString(bstrItemText);
      bResult = FALSE;
      DisplayErrorToUser();
   }

   return bResult;
}

See Also

IXMLDOMElement Interface