Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq to xml - get rid of blank xmlns

Tags:

c#

xml

linq

I'm trying to get rid of empty namespace tags in my xml file. All of the solutions i've seen are based creating the xml from scratch. I have various xelements constructed from a previous xml. All I'm doing is

XElement InputNodes = XElement.Parse(InputXML);
m_Command = InputNodes.Element("Command");

and it adding the xmlns = "" everywhere. This is really infuriating. Thanks for any help.

like image 484
Steve Avatar asked Mar 01 '23 19:03

Steve


1 Answers

There's a post on MSDN blogs that shows how to get around this (reasonably) easily. Before outputing the XML, you'll want to execute this code:

foreach (XElement e in root.DescendantsAndSelf())
{
    if (e.Name.Namespace == string.Empty)
    {
        e.Name = ns + e.Name.LocalName;
    }
}

The alternative, as the poster mentions, is prefixing every element name with the namespace as you add it, but this seems like a nicer solution in that it's more automated and saves a bit of typing.

like image 57
Noldorin Avatar answered Mar 07 '23 17:03

Noldorin