GeckoFx (4)使用 treeview 展示 dom 数树
使用 DocumentCompleted 事件,在页面加载完成后构建一个 dom 树使用 treeview 控件。
treeHtml: treeview 控件;
browser:Gecko.GeckoWebBrowser 控件;
注册事件:
使用 DocumentCompleted 事件,在页面加载完成后构建一个 dom 树使用 treeview 控件。
treeHtml: treeview 控件;
browser:Gecko.GeckoWebBrowser 控件;
注册事件:
browser.DocumentCompleted += browser_DocumentCompleted;
/// <summary>
/// 文档加载完成事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void browser_DocumentCompleted(object sender, Gecko.Events.GeckoDocumentCompletedEventArgs e)
{
ShowHtmlTree();
}
/// <summary>
/// 构建dom树
/// </summary>
private void ShowHtmlTree()
{
this.treeHtml.Nodes.Clear();
var domRoot = browser.DomDocument;
StringBuilder attrStr = new StringBuilder();
Func<GeckoNode, string> getTag = (node) =>
{
attrStr.Clear();
if (node.NodeName.Equals("STYLE") ||
node.NodeName.Equals("SCRIPT"))
{
return string.Format("<{0}>...</{0}>",node.NodeName.ToLower());
}
//var element = node as GeckoHtmlElement;
string innerText = string.Empty;
GeckoElement element = node.GetEventTarget().CastToGeckoElement();
//
if (element != null &&
element.ChildNodes.Count()==1 &&
element.ChildNodes[0].NodeType == NodeType.Text)
{
innerText = element.TextContent;
}
attrStr.AppendFormat("<{0}", node.NodeName.ToLower());
//构建属性
if (node.HasAttributes && element != null)
{
foreach (var attr in element.Attributes)
{
attrStr.Append(
string.Format(" {0}=\"{1}\"", attr.NodeName, attr.NodeValue));
}
}
//内容
attrStr.AppendFormat(">{0}</{1}>", innerText, node.NodeName.ToLower());
return attrStr.ToString();
};
//递归构建树
Func<GeckoNode, TreeNode> buildTree = null;
buildTree = (rNode) =>
{
if (rNode == null)
return null;
TreeNode tnode = new TreeNode()
{
Text = getTag(rNode),
Tag = rNode
};
if (rNode.ChildNodes == null || !rNode.ChildNodes.Any())
return null;
foreach (var cNode in rNode.ChildNodes)
{
var ctnode = buildTree(cNode);
if (ctnode != null)
tnode.Nodes.Add(ctnode);
}
return tnode;
};
var treeRoot = buildTree(domRoot);
if (treeRoot!=null)
this.treeHtml.Nodes.Add(treeRoot);
this.treeHtml.ExpandAll();
}