由於最近需要使用C#處理IE的相關操作,因此積累了一些代碼,下面的代碼是從Html代碼中生成DOM TreeVIEw的例子:
//該過程將被遞歸調用
//dom_node是當前的Html DOM節點
//tree_node是當前插入樹的結點
private void InsertDOMNodes(IHtmlDOMNode parentnode,TreeNode tree_node)
{
int sibing=0;//當前結點在兄弟結點之間的順序,所有的結點之間通過","隔開
if(parentnode.hasChildNodes())
{
//level++;
//pathstring = pathstring +","+ level;
IHTMLDOMChildrenCollection allchild = (IHtmlDOMChildrenCollection)parentnode.childNodes;
int length = allchild.length;
for(int i=0;i<length;i++)
{
string instring = pathstring;
instring = instring +","+ sibing++;
IHTMLDOMNode child_node = (IHtmlDOMNode)allchild.item(i);
TreeNode tempnode = tree_node.Nodes.Add(child_node.nodeName +"_"+instring);
//string tmp =
InsertDOMNodes(child_node,tempnode);
pathstring = instring;
}
}
}
private void eVIPSBrowser_DocumentComplete(object sender, AxSHDocVw.DWebBrowserEvents2_DocumentCompleteEvent e)
{
pathstring ="0";
level = 0;
DOMTreeVIEw.Nodes.Clear();
IHTMLDocument3 HTMLDocument =(IHtmlDocument3)eVIPSBrowser.Document;
IHTMLDOMNode rootDomNode = (IHTMLDOMNode)HtmlDocument.documentElement;
TreeNode root = DOMTreeVIEw.Nodes.Add("Html"+"_"+pathstring);
InsertDOMNodes(rootDomNode,root);
}