如果要是连接到 IE 的实例中,我可以利用 IHTMLDocument2 接口取得各种标签的内容,但是如果我只是在程序中需要一个解析器,从文件中读数据,并不开 IE 呢? 以下是我在一个按钮的 CLICK 消息中想从文件里取得 A 标签的 HREF:
#include <objidl.h>
#include <atlcomcli.h>
#include <mshtml.h>
#include <ExdispID.h>
#include <Exdisp.h>.
.
. UpdateData(TRUE);
USES_CONVERSION; CComQIPtr<IHTMLDocument2,&IID_IHTMLDocument2> spHTMLDoc;
HRESULT hr;

hr=spHTMLDoc.CoCreateInstance(CLSID_HTMLDocument);
if(FAILED(hr)) return; //CComPtr<IWebBrowser2> spWebBrs2;
//hr=spWebBrs2.CoCreateInstance(CLSID_WebBrowser);
//CComPtr<IDispatch> spDisp2;
//spWebBrs2->get_Document(&spDisp2); //spHTMLDoc=spDisp2; CComPtr<IPersistFile> spPstFile;
spPstFile=spHTMLDoc;

//spPstFile=spWebBrs2; if(spPstFile) {
hr=spPstFile->Load(m_sHTMLPath,0);
if(FAILED(hr)) return; CComBSTR bstrURL;
spHTMLDoc->get_URL(&bstrURL);
spHTMLDoc->get_fileSize(&bstrURL);
spHTMLDoc->get_title(&bstrURL); //CComPtr<IHTMLElement> spHTMLElem;
//hr=spHTMLDoc->get_body(&spHTMLElem); CComPtr<IHTMLElementCollection> spElemColl;
//hr=spHTMLDoc->get_anchors(&spElemColl);
hr=spHTMLDoc->get_all(&spElemColl);
//hr=spHTMLElem->get_title(&bstrURL);//->get_anchors(&spElemColl);
if(FAILED(hr)) return; CComPtr<IDispatch> spDisp;
CComPtr<IHTMLAnchorElement> spAnchor; long len;
spElemColl->get_length(&len);

CComBSTR bstrHref;
CComVariant index;
for(long i=0;i<len;i++) {
index=i;
spElemColl->item(index,index,&spDisp);
spAnchor=spDisp; if(spAnchor) {
spAnchor->get_href(&bstrHref);
TRACE(_T("* Archor: %s\n"),bstrHref);
}
spDisp.Release();
}
}
else AfxMessageBox(_T("无法载入 HTML 文件!"));
结果取得的 len 总是0。 后来我发现好像是 IPersistFile 只把文件读了进去,没有进行解析。不知道那位大侠对此有研究??