可能重复:
在 C# 中解析 html 的最佳方法是什么?
我正在解析一个 HTML 文件。我需要在 html 中找到所有 href 标记并将它们替换为文本友好的版本。
这是一个例子。
Original Text: <a href="http://foo.bar">click here</a>
replacement value: click here <http://foo.bar>
我如何实现这一目标?
可能重复:
在 C# 中解析 html 的最佳方法是什么?
我正在解析一个 HTML 文件。我需要在 html 中找到所有 href 标记并将它们替换为文本友好的版本。
这是一个例子。
Original Text: <a href="http://foo.bar">click here</a>
replacement value: click here <http://foo.bar>
我如何实现这一目标?
您可以使用Html Agility Pack library,代码如下:
HtmlDocument doc = new HtmlDocument();
doc.Load(myHtmlFile); // load your file
// select recursively all A elements declaring an HREF attribute.
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//a[@href]"))
{
node.ParentNode.ReplaceChild(doc.CreateTextNode(node.InnerText + " <" + node.GetAttributeValue("href", null) + ">"), node);
}
doc.Save(Console.Out); // output the new doc.