Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate tag prefixes using XmlSerializer

Tags:

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 ?

like image 764
hoang Avatar asked May 11 '10 12:05

hoang


People also ask

How do you add a prefix in XML?

When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".

How does the XmlSerializer work C#?

The XmlSerializer creates C# (. cs) files and compiles them into . dll files in the directory named by the TEMP environment variable; serialization occurs with those DLLs. These serialization assemblies can be generated in advance and signed by using the SGen.exe tool.

What is Xmlelement namespace?

XML namespaces provide a method for qualifying the names of XML elements and XML attributes in XML documents. A qualified name consists of a prefix and a local name, separated by a colon. The prefix functions only as a placeholder; it is mapped to a URI that specifies a namespace.

Is a Namespsace for XML serialization?

The central class in the namespace is the XmlSerializer class. To use this class, use the XmlSerializer constructor to create an instance of the class using the type of the object to serialize. Once an XmlSerializer is created, create an instance of the object to serialize.


1 Answers

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); 
like image 80
Oded Avatar answered Sep 20 '22 09:09

Oded