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!!!
Comments
Anonymous
March 25, 2008
PingBack from http://msdnrss.thecoderblogs.com/2008/03/25/linq-to-xml-adding-namespace-quickly/Anonymous
March 25, 2008
Is the code for "square" a typo for "i*i" by any chance?Anonymous
March 26, 2008
@Kevin, Yup it was. I have corrected it. Thanks for the pointer. WrijuAnonymous
April 23, 2008
Welcome to the forty-third issue of Community Convergence. The last few weeks have been consumed by theAnonymous
July 12, 2011
i am trying to do the same in vb.net can you please guide me the same thing in vb.net?Anonymous
April 02, 2012
This fixed a problem whom I was struggling with for a while! Thank you very much!