读取Html标签到树中
![](images/attachicons/rar.gif)
WebBrowser 控件为 WebBrowser ActiveX 控件提供了托管包装。托管包装使您可以在 Windows 窗体客户端应用程序中显示网页。使用 WebBrowser 控件,可以复制应用程序中的 Internet Explorer Web 浏览功能,还可以禁用默认的 Internet Explorer 功能,并将该控件用作简单的 HTML 文档查看器。此外,可以使用该控件将基于 DHTML 的用户界面元素添加到窗体中,还可以隐瞒这些元素在 WebBrowser 控件中承载的事实。通过这种方法,可以将 Web 控件和 Windows 窗体控件无缝地整合到一个应用程序中。下面演示的是一个把html文档读到树中。
![](zzz/editor/img/code.gif)
/* * Created by SharpDevelop. * User: Administrator * Date: 2010-11-24 * Time: 10:44 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace HtmlDom { /// <summary> /// Description of MainForm. /// </summary> public partial class MainForm : Form { public MainForm() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); // // TODO: Add constructor code after the InitializeComponent() call. // } AboutForm aFrm=new AboutForm(); void MainFormLoad(object sender, EventArgs e) { aFrm.Show(); UrlText.Width=toolStrip1.Width -(toolStripButton1.Width+toolStripButton2.Width+toolStripLabel1.Width+50); } void MainFormResize(object sender, EventArgs e) { UrlText.Width=toolStrip1.Width -(toolStripButton1.Width+toolStripButton2.Width+toolStripLabel1.Width+50); } void ToolStripButton1Click(object sender, EventArgs e) { webBrowser1.Navigate(UrlText.Text); while(webBrowser1.ReadyState!=){ Application.DoEvents(); } treeView1.Nodes.Clear(); TreeNode node=new TreeNode(); toolStripProgressBar1.Value=0; toolStripProgressBar1.Minimum=0; toolStripProgressBar1.Maximum=webBrowser1.Document.All.Count; GetDom(node,webBrowser1.Document.GetElementsByTagName("html")); treeView1.Nodes.Add(node.FirstNode); } void GetDom(TreeNode node,HtmlElementCollection html){ foreach(HtmlElement he in html){ TreeNode tmp=node.Nodes.Add("<"+he.OuterHtml.Split(new char[]{'<'})[1]); if(he.CanHaveChildren){ GetDom(tmp,he.Children); } toolStripProgressBar1.Value+=1; } } void ToolStripButton2Click(object sender, EventArgs e) { aFrm.Show(); } } }
[ 本帖最后由 ioriliao 于 2010-11-25 19:33 编辑 ]