如何在C#中以最快的方式检索HTMLDocument的所有文本节点?
我需要在HTMLDocument的所有文本节点上执行一些逻辑。我目前就是这样做的:如何在C#中以最快的方式检索HTMLDocument的所有文本节点?,c#,dom,C#,Dom,我需要在HTMLDocument的所有文本节点上执行一些逻辑。我目前就是这样做的: HTMLDocument pageContent = (HTMLDocument)_webBrowser2.Document; IHTMLElementCollection myCol = pageContent.all; foreach (IHTMLDOMNode myElement in myCol) { foreach (IHTMLDOMNode child in (IHTMLDOMChildren
HTMLDocument pageContent = (HTMLDocument)_webBrowser2.Document;
IHTMLElementCollection myCol = pageContent.all;
foreach (IHTMLDOMNode myElement in myCol)
{
foreach (IHTMLDOMNode child in (IHTMLDOMChildrenCollection)myElement.childNodes)
{
if (child.nodeType == 3)
{
//Do something with textnode!
}
}
}
因为mycl中的一些元素也有子元素,它们本身也在mycl中,所以我不止一次地访问了一些节点!一定有更好的方法可以做到这一点?最好在递归函数中迭代子节点(直接子代),从顶层开始,类似于:
HtmlElementCollection collection = pageContent.GetElementsByTagName("HTML");
IHTMLDOMNode htmlNode = (IHTMLDOMNode)collection[0];
ProcessChildNodes(htmlNode);
private void ProcessChildNodes(IHTMLDOMNode node)
{
foreach (IHTMLDOMNode childNode in node.childNodes)
{
if (childNode.nodeType == 3)
{
// ...
}
ProcessChildNodes(childNode);
}
}
您可以在中使用XPath一次性访问所有文本节点 我认为这将工作如图所示,但还没有尝试过这一点
using HtmlAgilityPack;
HtmlDocument htmlDoc = new HtmlDocument();
// filePath is a path to a file containing the html
htmlDoc.Load(filePath);
HtmlNodeCollection coll = htmlDoc.DocumentNode.SelectNodes("//text()");
foreach (HTMLNode node in coll)
{
// do the work for a text node here
}