解析html程式(C#版)——遍歷各個節點(mshtml)
/*
在專案裡引用了mshtml.dll,並且引用名稱空間:using mshtml;
首先,引數html就是html文字內容(裡面有markup標記和顯示文字等等)
其次,getHtmlDisplayContent這個函式就是獲取html裡瀏覽器上可看到的內容,即從原始碼中取出顯示文字。
最後,traverseNodes是個人寫的一個遍歷各個節點的一個小小遞迴程式,沒考慮效率什麼的,只是想知道怎麼使用IHtmlDocument2和IHtmlDocument3介面
Note:當html文件不規範時,比如在<!Document....之前還有別的標記或者符號時,載入工作受到嚴重影響,此時估計是解析不出來了,我開始還不知道為什麼解析有些html時卡住了,原來是因為這些html文件在html標記前有\n\n\n....等。。。
*/
private static string getHtmlDisplayContent(string html)
{
string cont = "";
mshtml.HTMLDocumentClass oc = new mshtml.HTMLDocumentClass();
mshtml.IHTMLDocument2 doc2 = oc;
doc2.write(html);
mshtml.IHTMLDocument3 HTMLDocument = (mshtml.IHTMLDocument3)doc2;
traverseNodes(HTMLDocument.documentElement, ref cont);
//mshtml.IHTMLTitleElement title = (mshtml.IHTMLTitleElement)doc2.title;
/* cont += doc2.title.ToString();
mshtml.IHTMLBodyElement body = (mshtml.IHTMLBodyElement)doc2.body;
if (body.text!=null)
cont += body.text.ToString();
* */
doc2.close();
return cont;
}
private static void traverseNodes(mshtml.IHTMLElement parentNode,ref string cont)
{
if (parentNode.innerText!=null)
cont += parentNode.innerText;
mshtml.IHTMLElementCollection nodes = (IHTMLElementCollection)parentNode.children;
IEnumerator ienum= nodes.GetEnumerator();
while (ienum.MoveNext())
{
IHTMLElement node = (IHTMLElement)ienum.Current;
traverseNodes(node,ref cont);
}
}