To remove the namespace from an XML

To remove the namespace from an XML, use the following function (User XML.LINQ namespace)

 

public static XDocument RemoveNamespace(XDocument xDocument)

        {

            foreach (XElement oElement in xDocument.Root.DescendantsAndSelf())

            {

                if (oElement.Name.Namespace != XNamespace.None)

                {

                    oElement.Name = XNamespace.None.GetName(oElement.Name.LocalName);

                }

                if (oElement.Attributes().Where(a => a.IsNamespaceDeclaration || a.Name.Namespace != XNamespace.None).Any())

                {

                    oElement.ReplaceAttributes(oElement.Attributes().Select(a => a.IsNamespaceDeclaration ? null : a.Name.Namespace != XNamespace.None ? new XAttribute(XNamespace.None.GetName(a.Name.LocalName), a.Value) : a));

                }

            }

 

            return xDocument;

        }

 

Comments