Wriju's BLOG

.NET, Cloud and everything

LINQ to XML : Adding Namespace quickly

I have written a post earlier on how to attach Namespaces. After reading my article someone complained about the redundancy of the code. I also realized the pain. I was reading the book C# 3.0 In a Nutshell. There I got a very elegant solution. Let me explain the scenario,


 


If you create a XML like,


 


<?xml version=1.0 encoding=utf-8 ?>


<numbers xmlns=urn:myns-com>


  <number value=1 square=1 xmlns=“” />


  <number value=2 square=4 xmlns=“” />


  <number value=3 square=9 xmlns=“” />


  <number value=4 square=16 xmlns=“” />


  <number value=5 square=25″ xmlns=“” />


  <number value=6 square=36 xmlns=“” />


  <number value=7 square=49 xmlns=“” />


  <number value=8 square=64 xmlns=“” />


  <number value=9 square=81 xmlns=“” />


  <number value=10 square=100 xmlns=“” />


</numbers>


 


By writing


 


XNamespace ns = XNamespace.Get(“urn:myns-com”);


 


XElement root = new XElement(ns+ “numbers”,


    from i in Enumerable.Range(1, 10)


    select new XElement(“number”,


        new XAttribute(“value”, i),


        new XAttribute(“square”, i*i)));


 


Now since we have not added ns in all the blocks it adds xmlns=”” in all the areas. We can avoid this by writing,


 


XNamespace ns = XNamespace.Get(“urn:myns-com”);


 


XElement root = new XElement(ns+ “numbers”,


    from i in Enumerable.Range(1, 10)


    select new XElement(ns + “number”,


        new XAttribute(“value”, i),


        new XAttribute(“square”, i*i)));


 


Sometimes this could be painful if the structure is more complicated.


 


So writers have given us a tip,


foreach (XElement e in root.DescendantsAndSelf())


{


    if (e.Name.Namespace == “”)


    {


        e.Name = ns + e.Name.LocalName;


    }


}


 


This will modify the existing Xml to


 


<?xml version=1.0 encoding=utf-8 ?>


<numbers xmlns=urn:myns-com>


  <number value=1 square=1 />


  <number value=2 square=4 />


  <number value=3 square=9 />


  <number value=4 square=16 />


  <number value=5 square=25 />


  <number value=6 square=36″ />


  <number value=7 square=49″ />


  <number value=8 square=64″ />


  <number value=9 square=81 />


  <number value=10 square=100 />


</numbers>


 


 


Namoskar!!!