How to remove all namespaces from XML with C#?

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

    I tried the first few solutions and didn't work for me. Mainly the problem with attributes being removed like the other have already mentioned. I would say my approach is very similar to Jimmy by using the XElement constructors that taking object as parameters.

    public static XElement RemoveAllNamespaces(this XElement element)
    {
        return new XElement(element.Name.LocalName,
                            element.HasAttributes ? element.Attributes().Select(a => new XAttribute(a.Name.LocalName, a.Value)) : null,
                            element.HasElements ? element.Elements().Select(e => RemoveAllNamespaces(e)) : null,
                            element.Value);
    }
    

提交回复
热议问题