在SyndicationFeed中覆盖根元素,向根元素添加命名空间。

4

我需要在我的rss(根)元素中添加新的命名空间,除了a10:

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

我正在使用一个SyndicationFeed类来序列化为RSS 2.0,然后我使用一个XmlWriter来输出这个feed。
var feed = new SyndicationFeed(
                    feedDefinition.Title,
                    feedDefinition.Description,
     .
     .
     .



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

我尝试在SyndicationFeed上添加AttributeExtensions,但它会将新命名空间添加到频道元素而不是根元素中。谢谢。

也许你可以先写入一个临时内存流,以便将内容加载到XmlDocument中,你可以在其中进行任何必要的修改。然后再将XML内容写入输出。 - Steve B
1个回答

4

很遗憾,格式化程序无法以您需要的方式进行扩展。

您可以使用中间的XmlDocument,在写入最终输出之前对其进行修改。

此代码将在最终xml输出的根元素中添加命名空间:

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());

谢谢,这正是我在寻找的内容,尽管我没有使用StringBuilder,而是只是使用了我的XmlWriter.Create(context.HttpContext.Response.Output, settings)。 - Amin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接