HTML到RichTextBox的明文与超链接

本文关键字:超链接 明文 RichTextBox HTML | 更新日期: 2023-09-27 18:16:53

阅读这么多关于不使用RegExes剥离HTML,我想知道如何得到一些链接到我的RichTextBox没有得到所有凌乱的HTML,也是在我从一些报纸网站下载的内容。

我有:来自报纸网站的HTML。

我想要的:文章在一个RichTextBox纯文本。但有链接(即用<Hyperlink NavigateUri="foo">bar</Hyperlink>代替<a href="foo">bar</a>)。

htmllagilitypack给我HtmlNode.InnerText(剥离所有HTML标签)和HtmlNode.InnerHtml(与所有标签)。我可以得到链接的Url和文本(s)与articlenode.SelectNodes(".//a"),但我怎么知道在哪里插入HtmlNode.InnerText的纯文本?

HTML到RichTextBox的明文与超链接

您可以这样做(使用示例控制台应用程序,但思路与Silverlight相同):

假设你有这样的HTML:

<html>
<head></head>
<body>
Link 1: <a href="foo1">bar</a>
Link 2: <a href="foo2">bar2</a>
</body>
</html>

那么下面的代码:

HtmlDocument doc = new HtmlDocument();
doc.Load(myFileHtm);
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//a"))
{
    // replace the HREF element in the DOM at the exact same place
    // by a deep cloned one, with a different name
    HtmlNode newNode = node.ParentNode.ReplaceChild(node.CloneNode("Hyperlink", true), node);
    // modify some attributes
    newNode.SetAttributeValue("NavigateUri", newNode.GetAttributeValue("href", null));
    newNode.Attributes.Remove("href");
}
doc.Save(Console.Out);

将输出如下:

<html>
<head></head>
<body>
Link 1: <hyperlink navigateuri="foo1">bar</hyperlink>
Link 2: <hyperlink navigateuri="foo2">bar2</hyperlink>
</body>
</html>