views:

88

answers:

2

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 ?

A: 

Take a look at Xml Serialization and namespace prefixes

James
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 <link> tag
hoang
+2  A: 

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
Thank you ! I understand my error :)
hoang