最近有一个项目,其中一块儿需要将下载到本地的html文件中的一些元素遍历解析出来,提取其值。
从网上下载了一个例子“遍历网页中所有元素”,例子不错,可惜只能遍历用IE打开的网页。而不能遍历本地的html文件,请教各位,怎么样才能实现通过IHTMLDocument2接口遍历?谢谢之极!急啊。。

解决方案 »

  1.   

    网上下载WalkAll的例子,看看如何在没有浏览器窗口的情况下使用DOM
      

  2.   

    用open()方法可直接打开本地HTML文件,用document属性为根遍历
      

  3.   

    已经解决了:
    CString CTestDlg::ParseElementFromResponse(CString strResponse)
    {
    CString strRet("");
    //declare our MSHTML variables and create a document
    MSHTML::IHTMLDocument2Ptr pDoc;
    MSHTML::IHTMLDocument3Ptr pDoc3;
    MSHTML::IHTMLElementCollectionPtr pCollection;
    MSHTML::IHTMLElementPtr pElement;

    HRESULT hr = CoCreateInstance(CLSID_HTMLDocument, NULL, CLSCTX_INPROC_SERVER, IID_IHTMLDocument2, (void**)&pDoc);

    //put the code into SAFEARRAY and write it into document
    SAFEARRAY* psa = SafeArrayCreateVector(VT_VARIANT, 0, 1);
    VARIANT *param;
    bstr_t bsData = (LPCTSTR)strResponse;
    hr = SafeArrayAccessData(psa, (LPVOID*)&param);
    param->vt = VT_BSTR;
    param->bstrVal = (BSTR)bsData;

    hr = pDoc->write(psa);
    hr = pDoc->close();

    SafeArrayDestroy(psa);

    //I'll use IHTMLDocument3 to retrieve tags. Note it is available only in IE5+
    //If you don't want to use it, u can just run through all tags in HTML
    //(IHTMLDocument2->all property)
    pDoc3 = pDoc;

    //display HREF parameter of every link (A tag) in ListBox
    pCollection = pDoc3->getElementsByTagName(L"input");
    for(long i=0; i<pCollection->length; i++)
    {
    pElement = pCollection->item(i, (long)0);
    if(pElement != NULL)
    {
    //second parameter says that you want to get text inside attribute as is
    strRet += (LPCTSTR)bstr_t(pElement->getAttribute("name", 2));
    strRet += "=";
    strRet += (LPCTSTR)bstr_t(pElement->getAttribute("value", 2));
    strRet += ";";
    }
    }
    return strRet;
    }不过,也非常感谢两位百忙之中的回复!