Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Namespaces to a SyndicationFeed rather than Individual Elements?

I have a class like this:

public static class MyFeedExtensions
{
    private readonly static XNamespace _namespace = XNamespace.Get(@"http://mynamespace");

    public static XElement MyElement(string value)
    {
        return new XElement(_namespace + "MyElement", value);
    }
}

I'm using it to generate an Atom Feed with custom Extensions:

var feed = new SyndicationFeed();
feed.ElementExtensions.Add(MyFeedExtensions.MyElement("Testing!"));

This works fine, except that the feed adds my namespace to the element:

<feed xmlns="http://www.w3.org/2005/Atom">
  <title type="text">Hello World!</title>
  <id>00000000-0000-0000-0000-000000000000</id>
  <updated>2011-03-01T01:00:53Z</updated>
  <MyElement xmlns="http://mynamespace">Testing!</MyElement>
</feed>

Is there a way to register a namespace with the feed instead, to get an output like this?

<feed xmlns="http://www.w3.org/2005/Atom" xmlns:my="http://mynamespace">
  <title type="text">Hello World!</title>
  <id>00000000-0000-0000-0000-000000000000</id>
  <updated>2011-03-01T01:00:53Z</updated>
  <my:MyElement>Testing!</my:MyElement>
</feed>

Ideally, I would like this also to work when I have SyndicationItems with ElementExtensions, as the feed should know about all the various namespaces.

(Edit: This is purely to reduce the Size of the XML and to make it easier to read for humans)

like image 649
Michael Stum Avatar asked Mar 01 '11 01:03

Michael Stum


1 Answers

Found the answer in this question and adapted it:

feed.AttributeExtensions.Add(
    new XmlQualifiedName("my",XNamespace.Xmlns.ToString()),
    MyFeedExtensions.Namespace.ToString());

Basically: Register a xmlns:my Attribute with the feed, it will pick up the namespace automatically on the elements even if they are added to a SyndicationItem within the feed.

Obscure, but neat!

like image 61
Michael Stum Avatar answered Sep 28 '22 09:09

Michael Stum