读了这么多关于not using RegExes for stripping HTML的文章,我想知道如何在我的RichTextBox中加入一些链接,而不是在我从一些报纸网站下载的内容中得到所有凌乱的html。
我有:来自报纸网站的HTML。
我想要的:将文章作为RichTextBox中的纯文本。而是使用链接(即用<Hyperlink NavigateUri="foo">bar</Hyperlink>替换<a href="foo">bar</a> )。
HtmlAgilityPack给了我HtmlNode.InnerText (去掉了所有的HTML标签)和HtmlNode.InnerHtml (带有所有的标签)。我可以使用articlenode.SelectNodes(".//a")获取链接的Url和文本,但是我如何知道在HtmlNode.InnerText的纯文本中插入它们的位置
任何提示都将不胜感激。
发布于 2013-06-03 21:55:22
下面是你如何做到这一点(使用一个样例控制台应用程序,但对于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>https://stackoverflow.com/questions/16897823
复制相似问题