LINQ to XML: suppressing redundant namespace attribute in child nodes

Posted by GSerg on Stack Overflow See other posts from Stack Overflow or by GSerg
Published on 2010-02-25T00:07:29Z Indexed on 2010/04/16 19:33 UTC
Read the original article Hit count: 214

Filed under:
|
|

If a node belongs to a namespace, it's children by default belong to the same namespace. So there's no need to provide an xmlns attribute on each child, which is good.

However.

If I create two nodes like this:

Dim parent = <parent xmlns="http://my.namespace.org"/>
Dim child = <child xmlns="http://my.namespace.org">value</child>

parent.Add(child)

Console.WriteLine(parent.ToString)

The result is this:

<parent xmlns="http://my.namespace.org">
  <child xmlns="http://my.namespace.org">value</child>
</parent>

But, if create them in a less convenient way:

Dim parent = <parent xmlns="http://my.namespace.org"/>
Dim child As New XElement(XName.Get("child", "http://my.namespace.org")) With {.Value = "value"}

parent.Add(child)

Console.WriteLine(parent.ToString)

The result is more desirable:

<parent xmlns="http://my.namespace.org">
  <child>value</child>
</parent>

Obviously, I'd prefer to use the first way because it is so much more intuitive and easy to code. There's also another reason to not use method 2 -- sometimes I need to create nodes with XElement.Parse, parsing a string that contains an xmlns attribute, which produces exactly same results as method 1.

So the question is -- how do I get the pretty output of method 2, creating nodes as in method 1? The only option I see is to create a method that would clone given XElement, effectively recreating it according to method 2 pattern, but that seems ugly. I'm looking for a more obvious solution I overlooked for some reason.

© Stack Overflow or respective owner

Related posts about linq-to-xml

Related posts about vb.net