How to remove all namespaces from XML with C#?

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

    For attributes to work the for loop for adding attribute should go after recursion, also need to check if IsNamespaceDeclaration:

    private static XElement RemoveAllNamespaces(XElement xmlDocument)
    {
        XElement xElement;
    
        if (!xmlDocument.HasElements)
        {
            xElement = new XElement(xmlDocument.Name.LocalName) { Value = xmlDocument.Value };
        }
        else
        {
            xElement = new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(RemoveAllNamespaces));
        }
    
        foreach (var attribute in xmlDocument.Attributes())
        {
            if (!attribute.IsNamespaceDeclaration)
            {
                xElement.Add(attribute);
            }
        }
    
        return xElement;
    }
    

提交回复
热议问题