LINQ to XML : Working with Namespaces

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",

    new XElement("child"));

Console.WriteLine(root);

 

The output will look like,

<root xmlns="urn:mynamespace-com">

  <child xmlns="" />

</root>

 

But this does not add namespace to child. So if you have to add namespace to child also,

 

XElement root = new XElement("{urn:mynamespace-com}root",

    new XElement("{urn:mynamespace-com}child"));

 

Then the output will look like,

<root xmlns="urn:munamespace-com">

  <child />

</root>

 

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!!!