Condividi tramite


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

Comments

  • Anonymous
    March 21, 2008
    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.

  • Anonymous
    March 21, 2008
    Based on my previous post on LINQ to XML : Working with Namespaces , if you want to add prefixes to your

  • Anonymous
    March 24, 2008
    How do you supress the xmlns="" from being included at all in the child element that is being added?

  • Anonymous
    March 24, 2008
    @seth I have supressed xmlns="" by XNamespace ns = XNamespace.Get("urn:mynamespace-com"); XElement root = new XElement(ns+"root",    new XElement(ns+"child"));

  • Anonymous
    March 25, 2008
    I have written a post earlier on how to attach Namespaces . After reading my article someone complained

  • Anonymous
    March 25, 2008
    @Yurik, Your answer is here, http://blogs.msdn.com/wriju/archive/2008/03/26/linq-to-xml-adding-namespace-quickly.aspx

  • Anonymous
    April 23, 2008
    Welcome to the forty-third issue of Community Convergence. The last few weeks have been consumed by the