views:

28

answers:

1

I have a webbrowser and I use DocumentComplete to read the current document from the WebBrowser (as IHTMLDocument2).

What's the easiest way to run xpath queries in that html doc? I am looking for something easy to use and lightweight.

I am using Visual Studio C++ 2010.

+1  A: 

What's the easiest way to run xpath queries in that html doc? I am looking for something easy to use and lightweight.

I am using Visual Studio C++ 2010.

Generally, XPath expressions cannot be evaluated against HTML documents.

However, if the HTML document is also an XHTML document (which is by definition a well-formed XML document), then XPath expressions can be evaluated against it.

In particular using MS Visual C++, one can use code like this:

#include <stdio.h>
#import <msxml3.dll>
using namespace MSXML2;

void dump_com_error(_com_error &e);

int main(int argc, char* argv[])
{
  CoInitialize(NULL);
  try{
    IXMLDOMDocument2Ptr pXMLDoc = NULL;
    HRESULT hr = pXMLDoc.CreateInstance(__uuidof(DOMDocument30));

    // Set parser property settings
    pXMLDoc->async =  VARIANT_FALSE;

    // Load the sample XML file
    hr = pXMLDoc->load("hello.xsl");

    // If document does not load report the parse error 
    if(hr!=VARIANT_TRUE)
    {
      IXMLDOMParseErrorPtr  pError;
      pError = pXMLDoc->parseError;
      _bstr_t parseError =_bstr_t("At line ")+ _bstr_t(pError->Getline())
      + _bstr_t("\n")+ _bstr_t(pError->Getreason());
      MessageBox(NULL,parseError, "Parse Error",MB_OK);
      return 0;
    }
    // Otherwise, build node list using SelectNodes 
    // and returns its length as console output
    else
      pXMLDoc->setProperty("SelectionLanguage", "XPath");
      // Set the selection namespace URI if the nodes
      // you wish to select later use a namespace prefix
      pXMLDoc->setProperty("SelectionNamespaces",
      "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'");
      IXMLDOMElementPtr pXMLDocElement = NULL;
      pXMLDocElement = pXMLDoc->documentElement;
      IXMLDOMNodeListPtr pXMLDomNodeList = NULL;
      pXMLDomNodeList = pXMLDocElement->selectNodes("//xsl:template");
      int count = 0;
      count = pXMLDomNodeList->length;
      printf("The number of <xsl:template> nodes is %i.\n", count);
  }
  catch(_com_error &e)
  {
    dump_com_error(e);
  }
  return 0;
}

void dump_com_error(_com_error &e)
{
  printf("Error\n");
  printf("\a\tCode = %08lx\n", e.Error());
  printf("\a\tCode meaning = %s", e.ErrorMessage());
  _bstr_t bstrSource(e.Source());
  _bstr_t bstrDescription(e.Description());
  printf("\a\tSource = %s\n", (LPCSTR) bstrSource);
  printf("\a\tDescription = %s\n", (LPCSTR) bstrDescription);
}

Read more about this code example here.

Dimitre Novatchev