# Friday, June 12, 2009
I am looking for the clean, elegant and smart solution to remove namespaces from all XML elements. How would function to do that look like?

I have used StackOverflow. If you do not know this site, I can describe it as a really smart Q&A site, dedicated for programmers.

So I was searching for really great solution for removement of namespaces in XML. Based on one programmer answer I have created a solution which I really likes. You can clearly see, when you have to deal with tree data structure (which XML for sure is) recursion is simply the best approach to do anything with it:
private static XElement RemoveAllNamespaces(XElement xmlDocument)
{
    if (!xmlDocument.HasElements)
    {
        XElement xElement = new XElement(xmlDocument.Name.LocalName);
        xElement.Value = xmlDocument.Value;
        return xElement;
    }
    return new XElement(xmlDocument.Name.LocalName, 
xmlDocument.Elements().Select(el => RemoveAllNamespaces(el))); }
Do you likes? I love it. :)

I was totally convinced that exists some more smart .NET framework function, with which I could help. But I was wrong. The best .NET can do is something like this:
XmlDocument doc = new XmlDocument()
doc.Load(ms);
doc.DocumentElement.Attributes.RemoveAll();
All this function do, is to remove all attributes on root element only ... You could repeat this on every node with help of XPath, but since those selected nodes are immutable, this is little help.

posted on Friday, June 12, 2009 9:12:44 PM (Central European Daylight Time, UTC+02:00)  #    Comments [0] Trackback