XElement - RemoveAllNamespaces
An XElement extension method that removes all namespaces described by @this.
public static void Main() { XDocument xDocument = null; using (var ms = new MemoryStream(Encoding.Default.GetBytes("<z:test xmlns:z=\"http://www.w3.org/TR/html4/\"><z:test2 /></z:test>"))) { xDocument = XDocument.Load(ms); } XElement root = xDocument.Root; int result1 = root.Elements("test2").ToList().Count; // return 0; Console.WriteLine(result1); //C# Extension Method: XElement - RemoveAllNamespaces root = root.RemoveAllNamespaces(); // remove the "z" namespace int result2 = root.Elements("test2").ToList().Count; // return 1; Console.WriteLine(result2); }
View Source
using System.Linq; using System.Xml.Linq; public static partial class Extensions { /// <summary> /// An XElement extension method that removes all namespaces described by @this. /// </summary> /// <param name="this">The @this to act on.</param> /// <returns>An XElement.</returns> public static XElement RemoveAllNamespaces(this XElement @this) { return new XElement(@this.Name.LocalName, (from n in @this.Nodes() select ((n is XElement) ? RemoveAllNamespaces(n as XElement) : n)), (@this.HasAttributes) ? (from a in @this.Attributes() select a) : null); } }