我在 C# 桌面应用程序中使用 MSIE WebBrowser
控件,并且正在寻找一种方法来构建和维护此控件之外的 HtmlElement
对象树。我试图在多个复杂页面之间快速切换,而不会产生每次都重新解析 HTML 的开销(而且我不想维护根据需要显示/隐藏的多个控件)。
我发现 a) 我只能通过控件的 HtmlDocument
创建 HtmlElement
对象和 b) 一旦我从控件的 HtmlDocument
,它“消失了”,即使我一直保持对根元素的强引用。
我该怎么做?
附言如果其他浏览器控件(例如 Gecko)允许我完成上述任务,我愿意考虑它们。
最佳答案
这样就可以了
// On screen webbrowser control
webBrowserControl.Navigate("about:blank");
webBrowserControl.Document.Write("<div id=\"div1\">This will change</div>");
var elementToReplace = webBrowserControl.Document.GetElementById("div1");
var nodeToReplace = elementToReplace.DomElement as mshtml.IHTMLDOMNode;
// In memory webbrowser control to load fragement into
// It needs this base object as it is a COM control
var webBrowserFragement = new WebBrowser();
webBrowserFragement.Navigate("about:blank");
webBrowserFragement.Document.Write("<div id=\"div1\">Hello World!</div>");
var elementReplacement = webBrowserFragement.Document.GetElementById("div1");
var nodeReplacement = elementReplacement.DomElement as mshtml.IHTMLDOMNode;
// The magic happens here!
nodeToReplace.replaceNode(nodeReplacement);
我怀疑这会提高性能,因为文本渲染器速度很快,如果您有一个大页面隐藏了 div,或者其他对象的内存中有多个 div,消耗的内存仍然是相同的?
关于html - 构建 HtmlElement 对象树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/631955/