#include <mshtml.h>
INT EnumHtmlElement(IDispatch *pDispDoc, CStringArray &m_listTags, CStringArray &m_listHref)
{
m_listTags.RemoveAll();
m_listHref.RemoveAll();
IHTMLDocument2* pHTMLDocument2 = NULL;
IHTMLElementCollection* pColl = NULL;
HRESULT hr;
LONG celem = 0;
if(pDispDoc)
pDispDoc->QueryInterface( IID_IHTMLDocument2, (void**)&pHTMLDocument2 );
if(pHTMLDocument2)
pHTMLDocument2->get_all( &pColl );
if(pColl)
pColl->get_length( &celem );
for ( int i=0; i< celem; i++ )
{
VARIANT varIndex;
varIndex.vt = VT_UINT;
varIndex.lVal = i;
VARIANT var2;
VariantInit( &var2 );
IDispatch* pDisp = NULL;
hr = pColl->item( varIndex, var2, &pDisp );
if (hr == S_OK)
{
IHTMLElement* pElem = NULL;
hr = pDisp->QueryInterface( IID_IHTMLElement, (void **)&pElem );
if ( hr == S_OK )
{
BSTR bstr;
hr = pElem->get_tagName(&bstr);
CString strTag = bstr;
IHTMLImgElement* pImgElem = NULL;
hr = pDisp->QueryInterface( IID_IHTMLImgElement, (void **)&pImgElem );
if ( hr == S_OK )
{
pImgElem->get_href(&bstr);
strTag += " - ";
strTag += bstr;
m_listHref.Add(bstr);
pImgElem->Release();
}
else
{
IHTMLAnchorElement* pAnchElem = NULL;
hr = pDisp->QueryInterface( IID_IHTMLAnchorElement, (void **)&pAnchElem );
if ( hr == S_OK )
{
pAnchElem->get_href(&bstr);
strTag += " - ";
strTag += bstr;
m_listHref.Add(bstr);
pAnchElem->Release();
}
}
m_listTags.Add( strTag );
pElem->Release();
}
pDisp->Release();
}
}
if(pColl)
{
pColl->Release(); pColl = NULL;
}
if(pHTMLDocument2)
{
pHTMLDocument2->Release(); pHTMLDocument2 = NULL;
}
if(pDispDoc)
{
pDispDoc->Release();
pDispDoc = NULL;
}
return (INT)m_listTags.GetSize();
}
//在HTMLView中测试
void CWebViewView::OnDocumentComplete(LPCTSTR lpszURL)
{
// TODO: Add your specialized code here and/or call the base class
LPDISPATCH pDisp = GetHtmlDocument();
CStringArray m_listTags, m_listHref;
if(EnumHtmlElement(pDisp, m_listTags, m_listHref) > 0)
{
TRACE(_T("\nTags\n"));
for(INT_PTR i=0; i<m_listTags.GetSize(); i++)
{
TRACE(_T("%s\n"), (LPCTSTR)m_listTags[i]);
}
TRACE(_T("\nhref\n"));
for(INT_PTR j=0; j<m_listHref.GetSize(); j++)
{
TRACE(_T("%s\n"), (LPCTSTR)m_listHref[j]);
}
}
pDisp->Release();
CHtmlView::OnDocumentComplete(lpszURL);
} |