How to remove all namespaces from XML with C#?

前端 未结 30 2224
悲哀的现实
悲哀的现实 2020-11-22 13:30

I am looking for the clean, elegant and smart solution to remove namespacees from all XML elements? How would function to do that look like?

Defined interface:

30条回答
  •  悲哀的现实
    2020-11-22 13:49

    Slightly modified Peter's answer, this would works fine for the attribute as well, including remove the namespace and prefix. A bit sorry for the code looks a bit ugly.

     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(new XAttribute(attribute.Name.LocalName, attribute.Value));
                    }
    
                    return xElement;
                }
    
                else
                {
                    XElement xElement = new XElement(xmlDocument.Name.LocalName,  xmlDocument.Elements().Select(el => RemoveAllNamespaces(el)));
    
                    foreach (XAttribute attribute in xmlDocument.Attributes())
                    {
                        xElement.Add(new XAttribute(attribute.Name.LocalName, attribute.Value));
                    }
    
                    return xElement;
                }
    
        }
    

提交回复
热议问题