Failed to remove empty xmlns attribute from XElement using C #

Before posting this question, I tried all the other solution on the stack, but without success.

I cannot remove the empty xmlns attribute from XElement using C #, I tried the following codes.

XElement.Attributes().Where(a => a.IsNamespaceDeclaration).Remove();

Another who posted here

foreach (var attr in objXMl.Descendants().Attributes())
{
    var elem = attr.Parent;
    attr.Remove();
    elem.Add(new XAttribute(attr.Name.LocalName, attr.Value));
}
+4
source share
3 answers

Image This is an xml file

<Root xmlns="http://my.namespace">
    <Firstelement xmlns="">
        <RestOfTheDocument />
    </Firstelement>
</Root>

Is that you expect

<Root xmlns="http://my.namespace">
    <Firstelement>
        <RestOfTheDocument />
    </Firstelement>
</Root>

I think the code below is what you want. You need to put each element in the correct namespace and remove any xmlns = '' attributes for the affected elements. The last part is required, since otherwise LINQ to XML basically tries to leave you with an element

<!-- This would be invalid -->
<Firstelement xmlns="" xmlns="http://my.namespace">

Here is the code:

using System;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        XDocument doc = XDocument.Load("test.xml");
        foreach (var node in doc.Root.Descendants())
        {
            // If we have an empty namespace...
            if (node.Name.NamespaceName == "")
            {
                // Remove the xmlns='' attribute. Note the use of
                // Attributes rather than Attribute, in case the
                // attribute doesn't exist (which it might not if we'd
                // created the document "manually" instead of loading
                // it from a file.)
                node.Attributes("xmlns").Remove();
                // Inherit the parent namespace instead
                node.Name = node.Parent.Name.Namespace + node.Name.LocalName;
            }
        }
        Console.WriteLine(doc); // Or doc.Save(...)
    }
}
+6

Xelement.Attribute , , "xmlns" .

Xelement.Attribute("xmlns").Value 
0

If you add the namespace of the parent element to the element, then the empty namespace tag will disappear because it is not required because the element is in the same namespace.

0
source

All Articles