C# - How to remove xmlns from XElement

2019-06-27 09: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:

<event xmlns="http://www.blablabla.com/bla" version="1.00">
  <retEvent version="1.00">
  </retEvent>
</event>

How can I accomplish this?

2条回答
SAY GOODBYE
2楼-- · 2019-06-27 09: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);
            }
        }
    } 
查看更多
ら.Afraid
3楼-- · 2019-06-27 10:00

You could use IsNamespaceDeclaration to detect which attribute is a namespace

xelement.Attributes()
        .Where( e => e.IsNamespaceDeclaration)
        .Remove();
查看更多
登录 后发表回答