SyndicationItem内容< >被编码为< >

时间:2012-04-11 21:31:19

标签: .net encoding rss syndication-item

我正在向我的SyndicationItem内容对象添加一些简单的标签,如

"<p>Hello World</p>"

但它在RSS Feed中显示为

"&lt;p&gtHello World&lt;/p&gt"

我尝试过不同的方法来避免这种情况,但都没有效果。

1 个答案:

答案 0 :(得分:1)

我已经看到了许多解决方案,这些解决方案适用于旧版本的.net:

SyndicationFeed: Content as CDATA?

此处还有后期处理解决方案:

https://gist.github.com/davidwhitney/1027181

第一个解决方案对我来说不可行,因为我们使用的是最新版本的.net,而第二个解决方案看起来很简单,所以我最终实现了这个解决方案:

public class CDataWriter : XmlTextWriter
{
    public CDataWriter(TextWriter w) : base(w) { }

    public CDataWriter(Stream w, Encoding encoding) : base(w, encoding) { }

    public CDataWriter(string filename, Encoding encoding) : base(filename, encoding) { }

    public override void WriteString(string text)
    {
        if (text.Contains("<") && text.Contains(">"))
        {
            base.WriteCData(text);
        }
        else
        {
            base.WriteString(text);
        }
    }

}

然后使用该课程:

public static class FeedToStringBuilder
{
    public static StringBuilder CDataOverwriteMethod(Rss20FeedFormatter formatter)
    {
        var buffer = new StringBuilder();
        var xmlWriterSettings = new XmlWriterSettings {Indent = true};
        using (var stream = new StringWriter(buffer))
        using (var writer = new CDataWriter(stream))
        using (var xmlWriter = XmlWriter.Create(writer, xmlWriterSettings))
        {
            formatter.WriteTo(xmlWriter);
        }
        return buffer;
    }
}

在控制器中使用:

public ActionResult RssFeed()
{
    SyndicationFeed feed;
    using (var dataContext = new DataContext())
    {
        string urlBase = $"{Request.Url.Scheme}://{Request.Url.Authority}{Request.ApplicationPath.TrimEnd('/')}/";
        feed = new PodcastFeed(dataContext, Server).GetFeed(urlBase);
    }

    var rss20FeedFormatter = new Rss20FeedFormatter(feed);
    rss20FeedFormatter.SerializeExtensionsAsAtom = false;

    var feedXml = FeedToStringBuilder.CDataOverwriteMethod(rss20FeedFormatter).ToString();
    return Content(feedXml, "text/xml");
}