我想在C#中将IHTMLDOMNode
转换为IHTMLElement
,我尝试了以下内容:
IHTMLElement tempElement = node as IHTMLElement;
//node is a instance of IHTMLDOMNode internface
但是,这不起作用 - tempElement
是null
。有没有办法正确执行此转换?请注意,在我的应用程序中,我尝试使用WebBrowser
访问DOM树中的每个节点并获取它们的坐标。
这是我的源代码,你能告诉我该怎么做吗?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using mshtml;
namespace TestWindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.ScrollBarsEnabled = true;
webBrowser1.Url = new Uri("http://www.bing.com");
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HTMLDocument document = (HTMLDocument)webBrowser1.Document.DomDocument;
IHTMLDOMNode bodyNode = (IHTMLDOMNode)webBrowser1.Document.Body.DomElement;
TranversalDOM(document, bodyNode);
}
private void TranversalDOM(HTMLDocument document, IHTMLDOMNode node)
{
if (node.nodeType == 3)
{
string nodeInfo = node.nodeValue.ToString();
nodeInfo += ">>>";
IHTMLElement tempElement = node as IHTMLElement;
//how to convert IHTMLDOMNode to IHTMLElement?
int X1 = findPosX(tempElement);
int X2 = X1 + tempElement.offsetWidth;
int Y1 = findPosY(tempElement);
int Y2 = Y1 + tempElement.offsetHeight;
nodeInfo += " LeftTop: (";
nodeInfo += X1.ToString();
nodeInfo += ",";
nodeInfo += Y1.ToString();
nodeInfo += ")";
nodeInfo += " RightBottom: (";
nodeInfo += X2.ToString();
nodeInfo += ",";
nodeInfo += Y2.ToString();
nodeInfo += ")";
listBox1.Items.Add(nodeInfo);
}
else
{
IHTMLDOMChildrenCollection childNodes = node.childNodes as IHTMLDOMChildrenCollection;
foreach (IHTMLDOMNode n in childNodes)
{
TranversalDOM(document, n);
}
}
}
public int findPosX(IHTMLElement obj)
{
int curleft = 0;
if (obj.offsetParent != null)
{
while (obj.offsetParent != null)
{
curleft += obj.offsetLeft;
obj = obj.offsetParent;
}
}
return curleft;
}
public int findPosY(IHTMLElement obj)
{
int curtop = 0;
if (obj.offsetParent != null)
{
while (obj.offsetParent != null)
{
curtop += obj.offsetTop;
obj = obj.offsetParent;
}
}
return curtop;
}
}
}
答案 0 :(得分:2)
如果不是IHTMLElement
,则无法转换。
答案 1 :(得分:-1)
我不熟悉这些界面,但您可以尝试:
IHTMLElement tempElement = (IHTMLElement)node;