How to remove all namespaces from XML with C#?

前端 未结 30 2544
悲哀的现实
悲哀的现实 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:45

    Well, here is the final answer. I have used great Jimmy idea (which unfortunately is not complete itself) and complete recursion function to work properly.

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

    It's working 100%, but I have not tested it much so it may not cover some special cases... But it is good base to start.

提交回复
热议问题