• Home
  • C#
  • Remove Namespaces from XML Document

Remove Namespaces from XML Document

Below is how to remove the name spae references from an XML document. I found this useful because when I use NewtonSoft’s JSON Converter namespaces often cause issues.

using System.Xml;
using System.Xml.Linq;

void test(){
    string xml = File.ReadAllText(@"D:\TestXML\test.xml");
    string cleanXML = RemoveAllNamespaces(xml);
}

//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)));
}

Leave a Reply

Your email address will not be published. Required fields are marked *