Overwriting root element in syndicationfeed, Adding namespaces to root element

1.8k views Asked by At

I need to add new namespaces to the rss(root) element of my feed, in addition to a10:

<rss xmlns:a10="http://www.w3.org/2005/Atom" version="2.0">
    <channel>
.
.
.

I am using a SyndicationFeed class serialized to RSS 2.0 and I use a XmlWriter to output the feed,

var feed = new SyndicationFeed(
                    feedDefinition.Title,
                    feedDefinition.Description,
     .
     .
     .



using (var writer = XmlWriter.Create(context.HttpContext.Response.Output, settings))
        {
            rssFormatter.WriteTo(writer);
        }

I have tried adding AttributeExtensions on SyndicationFeed but it adds the new namespaces to the channel element instead of the root,

Thank you

1

There are 1 answers

1
jedigo On BEST ANSWER

Unfortunately the formatter is not extensible in the way you need.

You can use an intermediate XmlDocument and modify it before writing to the final output.

This code will add a namespace to the root element of the final xml output:

var feed = new SyndicationFeed("foo", "bar", new Uri("http://www.example.com"));
var rssFeedFormatter = new Rss20FeedFormatter(feed);

// Create a new  XmlDocument in order to modify the root element
var xmlDoc = new XmlDocument();

// Write the RSS formatted feed directly into the xml doc
using(var xw = xmlDoc.CreateNavigator().AppendChild() )
{
    rssFeedFormatter.WriteTo(xw);
}

// modify the document as you want
xmlDoc.DocumentElement.SetAttribute("xmlns:example", "www.example.com");

// now create your writer and output to it:
var sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb))
{
    xmlDoc.WriteTo(writer);
}

Console.WriteLine(sb.ToString());