Posted by: msqr | August 26, 2008

default namespace and prefix in Root node of XML

Desired XML string:

<ns0:Product xmlns:ns0=””><ProductID>12345</ProductID><ProductName>SC12345</ProductName></ns0:Product&gt;

here, ns0:Namespace prefix

xmlns=”; is the default namespace. When you have root node with namespace prefix, its called Qualified root. If you notice this xmlstring closely then it contains “”  All the elements do not have namespace prefix, i.e. they are unqualified in XML Lingo.

Let’s say you have a simple Product entity, decorated with XMLRoot

using System.Xml;
using System.Xml.Serialization;
using System.Text;
[XmlRoot(ElementName = “MyProduct”,IsNullable = false)]
public class Product
private int _productID;

[XmlElementAttribute(Form = XmlSchemaForm.Unqualified)]
public int ProductID
get { return _productID; }
set { _productID = value; }

private string _productName;

[XmlElementAttribute(Form = XmlSchemaForm.Unqualified)]
public string ProductName
get { return _productName; }
set { _productName = value; }


What about code to serialize Product entity to Desired XML?

public static string ToXML(Product prod)
XmlSerializerNamespaces ns=new XmlSerializerNamespaces();

XmlRootAttribute xRoot=new XmlRootAttribute();

//Create XMLWriter with Settings
XmlWriterSettings xwSettings=new XmlWriterSettings();

StringBuilder output=new StringBuilder();
XmlWriter xw=XmlWriter.Create(output,xwSettings);

//Serialize Product object to output
XmlSerializer x=new XmlSerializer(prod.GetType(),xRoot);
return output.ToString();

Feel free to dop your comments.



  1. […] – bookmarked by 1 members originally found by scruggsw on 2008-11-09 default namespace and prefix in Root node of XML – […]

  2. excellent writing .

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s


%d bloggers like this: