C# - How to remove xmlns from XElement

后端 未结 3 1853
野趣味
野趣味 2020-12-20 17:10

How can I remove the \"xmlns\" namespace from a XElement?

I tried: attributes.remove, xElement.Name.NameSpace.Remove(0), etc, etc. No success.

My xml:

<
3条回答
  •  暖寄归人
    2020-12-20 17:55

    The accepted answer did not work for me because xelement.Attributes() was empty, it wasn't returning the namespace as an attribute.

    The following will remove the declaration in your case:

    element.Name = element.Name.LocalName;

    If you want to do it recursively for your element and all child elements use the following:

        private static void RemoveAllNamespaces(XElement element)
        {
            element.Name = element.Name.LocalName;
    
            foreach (var node in element.DescendantNodes())
            {
                var xElement = node as XElement;
                if (xElement != null)
                {
                    RemoveAllNamespaces(xElement);
                }
            }
        } 
    

提交回复
热议问题