Posted by: msqr | August 26, 2008

default namespace and prefix in Root node of XML

Desired XML string:

<ns0:Product xmlns:ns0=”https://msqr.wordpress.com/Serialization/Product”><ProductID>12345</ProductID><ProductName>SC12345</ProductName></ns0:Product&gt;

here, ns0:Namespace prefix

xmlns=”https://msqr.wordpress.com/Serialization/Product&#8221; 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 “https://msqr.wordpress.com/Serialization/Product”  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();
ns.Add(nsPrefix,nsURI);

XmlRootAttribute xRoot=new XmlRootAttribute();
xRoot.Namespace=nsURI;

//Create XMLWriter with Settings
XmlWriterSettings xwSettings=new XmlWriterSettings();
xwSettings.OmitXmlDeclaration=true;
xwSettings.Encoding=Encoding.UTF8;

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

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

Feel free to dop your comments.


Responses

  1. […] – bookmarked by 1 members originally found by scruggsw on 2008-11-09 default namespace and prefix in Root node of XML https://msqr.wordpress.com/2008/08/26/default-namespace-and-prefix-in-root-node-of-xml/ – […]

  2. excellent writing .


Leave a comment

Categories