C#中从HTML生成DOM TreeView的代码
由于最近需要使用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);
}