4

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.

Steve
  • 11,763
  • 15
  • 70
  • 103

3 Answers3

8

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.

Noldorin
  • 144,213
  • 56
  • 264
  • 302
0

I think the second answer down on this post:

XElement Add function adds xmlns="" to the XElement

was very useful. Basically if you just do

XNamespace rootNamespace = doc.Root.Name.NamespaceName;
XElement referenceElement = new XElement(rootNamespace + "Reference");

That should solve it. So I guess you have to tell it not to worry about a special namespace when you are creating the element. Odd.

Community
  • 1
  • 1
Dan Csharpster
  • 2,662
  • 1
  • 26
  • 50
0

Possibly it's this: Empty namespace using Linq Xml

This would indicate your document is in a different default namespace than the elements you add.

Community
  • 1
  • 1
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • that's the issue, but I can't build my xelements that way because I've already gotten half of them from another xml document – Steve Apr 29 '09 at 18:38
  • You just have to make sure that the namespaces of the document and the elements you insert match. If they don't, every element that deviates from the default will get it's own xmlns attribute, so the difference gets persisted in the XML file. – Tomalak Apr 29 '09 at 18:41