Rico Strydom
Rico Strydom

Reputation: 571

Linq to Xml : Remove namespace

I am retrieving an element or node from my xml doc. All goes well but when I retrieve the node it gets assigned the namespace of my root. This I don't want. I just want the node as it was before (without namespace).

My element that is retrieve is e.g. xElement. I am tried

  1. xElement.Attributes("xmlns").Remove();
  2. xElement.Attributes("xmlns").Where(x=>x.IsNamespaceDeclaration).Remove();

None of them did the trick.

I even tried this example: https://social.msdn.microsoft.com/Forums/en-US/9e6f77ad-9a7b-46c5-97ed-6ce9b5954e79/how-do-i-remove-a-namespace-from-an-xelement?forum=xmlandnetfx This left met with an element with an empty namespace xmlns=""

Please help.

Upvotes: 2

Views: 2362

Answers (1)

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28413

As stated here

Based on interface:

string RemoveAllNamespaces(string xmlDocument);

I represent here final clean and universal C# solution for removing XML namespaces:

//Implemented based on interface, not part of algorithm
public static string RemoveAllNamespaces(string xmlDocument)
{
    XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument));

    return xmlDocumentWithoutNs.ToString();
}

//Core recursion function
 private static XElement RemoveAllNamespaces(XElement xmlDocument)
    {
        if (!xmlDocument.HasElements)
        {
            XElement xElement = new XElement(xmlDocument.Name.LocalName);
            xElement.Value = xmlDocument.Value;

            foreach (XAttribute attribute in xmlDocument.Attributes())
                xElement.Add(attribute);

            return xElement;
        }
        return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el)));
    }

Above solution still have two flase

  • It ignores attributes
  • It doesn't work with "mixed mode" elements

Here is another solution:

 public static XElement RemoveAllNamespaces(XElement e)
 {
    return new XElement(e.Name.LocalName,
      (from n in e.Nodes()
        select ((n is XElement) ? RemoveAllNamespaces(n as XElement) : n)),
          (e.HasAttributes) ? 
            (from a in e.Attributes() 
               where (!a.IsNamespaceDeclaration)  
               select new XAttribute(a.Name.LocalName, a.Value)) : null);
  }          

Sample code here.

Upvotes: 1

Related Questions