Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyndicationFeed: Content as CDATA?

I'm using .NET's SyndicationFeed to create RSS and ATOM feeds. Unfortunately, I need HTML content in the description element (the Content property of the SyndicationItem) and the formatter automatically encodes the HTML, but I'd rather have the entire description element wrapped in CDATA without encoding the HTML.

My (simple) code:

var feed = new SyndicationFeed("Title", "Description", 
               new Uri("http://someuri.com"));
var items = new List<SyndicationItem>();

var item = new SyndicationItem("Item Title", (string)null, 
               new Uri("http://someitemuri.com"));

item.Content = SyndicationContent.CreateHtmlContent("<b>Item Content</b>");

items.Add(item);
feed.Items = items;

Anybody an idea how I can do this using SyndicationFeed? My last resort is to "manually" create the XML for the feeds, but I'd rather use the built-in SyndicationFeed.

like image 508
Hannes Sachsenhofer Avatar asked Dec 01 '22 07:12

Hannes Sachsenhofer


2 Answers

This worked for me:

public class CDataSyndicationContent : TextSyndicationContent
{
    public CDataSyndicationContent(TextSyndicationContent content)
        : base(content)
    {}

    protected override void  WriteContentsTo(System.Xml.XmlWriter writer)
    {
        writer.WriteCData(Text);
    }
}

then you can:

new CDataSyndicationContent(new TextSyndicationContent(content, TextSyndicationContentKind.Html))
like image 154
cpowers Avatar answered Dec 04 '22 02:12

cpowers


For those for whom the solution provided by cpowers and WonderGrub also didn't work, you should check out the following SO question, because for me this question was actually the answer to my occurence of this problem! Rss20FeedFormatter Ignores TextSyndicationContent type for SyndicationItem.Summary

Judging from the positive answer from thelsdj and Andy Rose and then later the 'negative' response from TimLeung and the alternative offered by WonderGrub I would estimate that the fix offered by cpowers stopped working in some later version of ASP.NET or something.

In any case the solution in the above SO article (derived from David Whitney's code) solved the problem with unwanted HTML encoding in CDATA blocks in an RSS 2.0 feed for me. I used it in an ASP.NET 4.0 WebForms application.

like image 28
Bart Avatar answered Dec 04 '22 01:12

Bart