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 ?
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".
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With