23

I wanted to generate the following using XmlSerializer :

<atom:link href="http://dallas.example.com/rss.xml" rel="self" type="application/rss+xml" />

So I tried to add a Namespace to my element :

[...]

    [XmlElement("link", Namespace="atom")]
    public AtomLink AtomLink { get; set; }

[...]

But the output is :

<link xmlns="atom" href="http://dallas.example.com/rss.xml" rel="self" type="application/rss+xml" />

So what is the correct way to generate prefixed tags ?

hoang
  • 1,887
  • 1
  • 24
  • 34

2 Answers2

47

First off, the atom namespace is normally this:

xmlns:atom="http://www.w3.org/2005/Atom"

In order to get your tags to use the atom namespace prefix, you need to mark your properties with it:

[XmlElement("link", Namespace="http://www.w3.org/2005/Atom")]
public AtomLink AtomLink { get; set; }

You also need tell the XmlSerializer to use it (thanks to @Marc Gravell):

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("atom", "http://www.w3.org/2005/Atom");
XmlSerializer xser = new XmlSerializer(typeof(MyType));
xser.Serialize(Console.Out, new MyType(), ns);
Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • Hi, if I am using => new XmlSyndicationContent(contentType, content, serializerXml); where I cannot establish the namespaces. What can I do? I want the content of the atom entry be with namespaces :( – X.Otano Jul 27 '17 at 12:25
0

Take a look at Xml Serialization and namespace prefixes

Community
  • 1
  • 1
James
  • 80,725
  • 18
  • 167
  • 237
  • 1
    In fact I am already using this : XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("atom", "http://www.w3.org/2005/Atom"); serializer.Serialize(xmlWriter, _rss, ns); And it just adds xmlns:atom="http://www.w3.org/2005/Atom" as an attribute to my root element ... but no prefix to my tag – hoang May 11 '10 at 12:28