How to remove all namespaces from XML with C#?

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

    Another solution that takes into account possibly interleaving TEXT and ELEMENT nodes, e.g.:

    
        text1
        
        text2
        
    
    

    Code:

    using System.Linq;
    
    namespace System.Xml.Linq
    {
        public static class XElementTransformExtensions
        {
            public static XElement WithoutNamespaces(this XElement source)
            {
                return new XElement(source.Name.LocalName,
                    source.Attributes().Select(WithoutNamespaces),
                    source.Nodes().Select(WithoutNamespaces)
                );
            }
    
            public static XAttribute WithoutNamespaces(this XAttribute source)
            {
                return !source.IsNamespaceDeclaration
                    ? new XAttribute(source.Name.LocalName, source.Value)
                    : default(XAttribute);
            }
    
            public static XNode WithoutNamespaces(this XNode source)
            {
                return
                    source is XElement
                        ? WithoutNamespaces((XElement)source)
                        : source;
            }
        }
    }
    

提交回复
热议问题