If you are working with complex real world XML then you have to deal with namespaces to disambiguate. There are several ways to implement namespaces in LINQ to XML. One is you can use pure string to add your namespace with each element declaration, like
<root>
<child />
</root>
To create the above Xml you will be writing
XElement root = new XElement("root",
new XElement("child"));
To add namespace here, it is very simple
XElement root = new XElement("{urn:mynamespace-com}root",
Console.WriteLine(root);
The output will look like,
<root xmlns="urn:mynamespace-com">
<child xmlns="" />
But this does not add namespace to child. So if you have to add namespace to child also,
new XElement("{urn:mynamespace-com}child"));
Then the output will look like,
<root xmlns="urn:munamespace-com">
But this approach is redundant as you have to type {urn:mynamespace-com} everywhere to make that the part of the same namespace.
So to avoid this you can write some elegant code.
XNamespace ns = XNamespace.Get("urn:mynamespace-com");
XElement root = new XElement(ns+"root",
new XElement(ns+"child"));
This looks more elegant code.
Another Mike Taulty magic.
Namoskar!!!
It's strange there is no overloaded constructors with first parameter being the XNamespace. String concatenations are 1)ugly, 2)performance hogs - concatenating just to parse it back is a bit redundant IMHO.
Based on my previous post on LINQ to XML : Working with Namespaces , if you want to add prefixes to your
How do you supress the xmlns="" from being included at all in the child element that is being added?
@seth
I have supressed xmlns="" by
I have written a post earlier on how to attach Namespaces . After reading my article someone complained
@Yurik,
Your answer is here,
http://blogs.msdn.com/wriju/archive/2008/03/26/linq-to-xml-adding-namespace-quickly.aspx
Welcome to the forty-third issue of Community Convergence. The last few weeks have been consumed by the