SyndicationFeed: Content as CDATA?

2019-02-18 06:36发布

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.

9条回答
再贱就再见
2楼-- · 2019-02-18 07:23

Here is what we did :

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

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

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

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

       }

And then to use the class :

public StringBuilder CDataOverwiriteMethod(Rss20FeedFormatter formatter)
       {
           var buffer = new StringBuilder();

           //could be streamwriter as well
           using (var stream = new StringWriter(buffer))
           {
               using (var writer = new XmlCDataWriter(stream))
               {
                   var settings = new XmlWriterSettings() {Indent = true};

                   using (var xmlWriter = XmlWriter.Create(writer, settings))
                   {
                       formatter.WriteTo(xmlWriter);
                   }
               }
           }

           return buffer;
       }
查看更多
Animai°情兽
3楼-- · 2019-02-18 07:25

try this

XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = false;
            //settings.ProhibitDtd = false;
            using (XmlReader reader = XmlReader.Create(rssurl, settings))
查看更多
时光不老,我们不散
4楼-- · 2019-02-18 07:30

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))
查看更多
登录 后发表回答