How to remove all namespaces from XML with C#?

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

    The reply's by Jimmy and Peter were a great help, but they actually removed all attributes, so I made a slight modification:

    Imports System.Runtime.CompilerServices
    
    Friend Module XElementExtensions
    
         _
        Public Function RemoveAllNamespaces(ByVal element As XElement) As XElement
            If element.HasElements Then
                Dim cleanElement = RemoveAllNamespaces(New XElement(element.Name.LocalName, element.Attributes))
                cleanElement.Add(element.Elements.Select(Function(el) RemoveAllNamespaces(el)))
                Return cleanElement
            Else
                Dim allAttributesExceptNamespaces = element.Attributes.Where(Function(attr) Not attr.IsNamespaceDeclaration)
                element.ReplaceAttributes(allAttributesExceptNamespaces)
                Return element
            End If
    
        End Function
    
    End Module
    

提交回复
热议问题