使用 C# 以编程方式删除 HtmlElement 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/554233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing HtmlElement objects programmatically using C#
提问by Tony the Pony
In a WebBrowsercontrol, how do I remove HtmlElementobjects? There are no methods in the HtmlElementclass to accomplish this. As a workaround, I can create a "dummy" HtmlElement(without inserting it into the HtmlDocument), into which I then insert (via AppendChild) the HtmlElementobjects to be removed. This feels like a hack. Is there a better way to do this?
在WebBrowser控件中,如何删除HtmlElement对象?HtmlElement类中没有方法可以完成此操作。作为一种解决方法,我可以创建一个“虚拟” HtmlElement(不将其插入HtmlDocument),然后将要删除AppendChild的HtmlElement对象插入(通过)。这感觉就像一个黑客。有一个更好的方法吗?
P.S. I want to retain the HtmlElementin memory to be used later, not simply destroy it (which is what setting its parent's innerHtmlto an empty string would do)
PS我想保留HtmlElement内存以供以后使用,而不是简单地销毁它(这是将其父项设置innerHtml为空字符串的方法)
采纳答案by alexl
Look at this WebControl Heritance, with loads of feature: http://www.codeproject.com/KB/miscctrl/csEXWB.aspx
看看这个具有大量功能的 WebControl 继承:http: //www.codeproject.com/KB/miscctrl/csEXWB.aspx
You could add a remove method to del element by id.
您可以通过 id 向 del 元素添加删除方法。
Hope this helps
希望这可以帮助
回答by configurator
回答by Tony the Pony
There's a method called IHTMLDOMNode::removeNodewhich looks like the "official" way to do this, but this is unmanaged code in mshtml.dll. I'm looking for something more suitable for C#.
有一个方法被调用IHTMLDOMNode::removeNode,它看起来像“官方”的方法来做到这一点,但这是mshtml.dll. 我正在寻找更适合 C# 的东西。
回答by Gerhard
You can delete the element by setting its outerhtml to an empty string.
您可以通过将其 outerhtml 设置为空字符串来删除该元素。
elem.OuterHtml = ""
elem.OuterHtml = ""
I hope this is what you were looking for.
我希望这就是你要找的。
gm
通用汽车
回答by alexl
Add a reference to Microsoft.mshtml (from .Net tab)
添加对 Microsoft.mshtml 的引用(来自 .Net 选项卡)
using Microsoft.mshtml;
....
{
...
// To Remove
HTMLDocumentClass htmldoc = wbCtrl.Document.DomDocument as HTMLDocumentClass;
IHTMLDOMNode node = htmldoc.getElementById("xBar") as IHTMLDOMNode;
node.parentNode.removeChild(node);
...
}

