Showing results for remove xmlns from xml c#
Search instead for remove xmlns from xml c

Well, here is the final answer. I have used great Jimmy idea (which unfortunately is not complete itself) and complete recursion function to work properly.

Based on interface:

string RemoveAllNamespaces(string xmlDocument);

I represent here final clean and universal C# solution for removing XML namespaces:

//Implemented based on interface, not part of algorithm
public static string RemoveAllNamespaces(string xmlDocument)
{
    XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument));

    return xmlDocumentWithoutNs.ToString();
}

//Core recursion function
 private static XElement RemoveAllNamespaces(XElement xmlDocument)
    {
        if (!xmlDocument.HasElements)
        {
            XElement xElement = new XElement(xmlDocument.Name.LocalName);
            xElement.Value = xmlDocument.Value;

            foreach (XAttribute attribute in xmlDocument.Attributes())
                xElement.Add(attribute);

            return xElement;
        }
        return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el)));
    }

It's working 100%, but I have not tested it much so it may not cover some special cases... But it is good base to start.

Answer from Peter Stegnar on Stack Overflow
Top answer
1 of 16
122

Well, here is the final answer. I have used great Jimmy idea (which unfortunately is not complete itself) and complete recursion function to work properly.

Based on interface:

string RemoveAllNamespaces(string xmlDocument);

I represent here final clean and universal C# solution for removing XML namespaces:

//Implemented based on interface, not part of algorithm
public static string RemoveAllNamespaces(string xmlDocument)
{
    XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument));

    return xmlDocumentWithoutNs.ToString();
}

//Core recursion function
 private static XElement RemoveAllNamespaces(XElement xmlDocument)
    {
        if (!xmlDocument.HasElements)
        {
            XElement xElement = new XElement(xmlDocument.Name.LocalName);
            xElement.Value = xmlDocument.Value;

            foreach (XAttribute attribute in xmlDocument.Attributes())
                xElement.Add(attribute);

            return xElement;
        }
        return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el)));
    }

It's working 100%, but I have not tested it much so it may not cover some special cases... But it is good base to start.

2 of 16
68

The tagged most useful answer has two flaws:

  • It ignores attributes
  • It doesn't work with "mixed mode" elements

Here is my take on this:

 public static XElement RemoveAllNamespaces(XElement e)
 {
    return new XElement(e.Name.LocalName,
      (from n in e.Nodes()
        select ((n is XElement) ? RemoveAllNamespaces(n as XElement) : n)),
          (e.HasAttributes) ? 
            (from a in e.Attributes() 
               where (!a.IsNamespaceDeclaration)  
               select new XAttribute(a.Name.LocalName, a.Value)) : null);
  }          

Sample code here.

🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 857792 › how-to-remove-the-xmlns-attribute-that-gets-added
how to remove the xmlns attribute that gets added by the xmldocument - Microsoft Q&A
May 20, 2022 - newElem = xmlDocument.CreateNode("element", "newnode", ""); //creates the node newElem.InnerText ="test" ; nodeList[0].AppendChild(newElem); //appends the node string data = xmlDocument.OuterXml; //while assiging the xmldocument to a string variable , its adding attribute xmlns="" to the newnode added · output: <newnode xmlns="">test<newnode> how we can remove the attribute xmlns="" that got added by the xml document?
Discussions

C# XML without declaration and namespace
I have already written the code to serialize the type as XML, this one line did the magic. It removed the xmlns (xml namespace) attribute from the generated XML. More on learn.microsoft.com
🌐 learn.microsoft.com
3
0
How to remove System.Xml.XmlElement (not XElement) Outerxml xmlns?
I've read : https://stackoverflow.com/questions/987135/how-to-remove-all-namespaces-from-xml-with-c https://stackoverflow.com/questions/35239773/how-to-remove-xmlns-tag https://stackoverflow.co... More on github.com
🌐 github.com
1
March 5, 2021
c# - Remove xmlns attribute from xml - Stack Overflow
In below Xml, I tried to delete the xmlns attribute but, its unable to populate under, xmlNode.Attributes still appear under OuterXml and final XmlDocument. ... More on stackoverflow.com
🌐 stackoverflow.com
c# - How to remove xmlns attribute of a node other than root in an XDocument? - Stack Overflow
I've been attempting to update a VSTO Outlook ribbon.xml and this code snippet did the trick 2020-08-15T21:51:18.837Z+00:00 ... Save this answer. Show activity on this post. There is no need to 'remove' the empty xmlns attribute. The whole reason that the empty xmlns attrib is added is because the namespace of your childnodes is empty (= '') and therefore differ from ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
The Coding Forums
thecodingforums.com › archive › archive › xml
How to remove xmlns attribute from XML document (.net) | XML | Coding Forums
May 8, 2006 - If you want to remove a namespace by processing the document as XML it's going to be tedious, since you're changing all the elements to be in a different namespace. You can't just remove the attribute unless there's some way to disable namespace processing, because once you've parsed the file it has already had its effect on all the other elements. -- Richard ... 1. Read the file 2. look for xmlns="..." 3.
Top answer
1 of 3
3

@Markus Freitag To override the behaviour of XmlSerializer you need XmlWriterSettings for override or remove XML declaration and XmlSerializerNamespaces for override namespace:

public static string ToXML(this T obj)  
{  
 // Remove Declaration  
 var settings = new XmlWriterSettings  
        {  
             Indent = true,  
             OmitXmlDeclaration = true  
        };  
  
 // Remove Namespace  
    var ns = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });  
  
    using (var stream = new StringWriter())  
    using (var writer = XmlWriter.Create(stream, settings))  
    {  
        var serializer = new XmlSerializer(typeof(T));  
        serializer.Serialize(writer, obj, ns);  
        return stream.ToString();  
    }  
}  

See full example here.

2 of 3
1

The most natural and easy way to implement it is via XSLT.
Please find below an example of it.

The XSLT is generic. It will remove (1) XML prolog declaration, and (2) any namespace(s) from any XML file.

Input XML



   
      
   

XSLT



 

 
 
 
 
 

 
 
 
 
 

 
 
 
 
 

Output XML


 
 
 

c# to launch XSLT transformation

void Main()
{
   const string SOURCEXMLFILE = @"e:\Temp\UniversalShipment.xml";
   const string XSLTFILE = @"e:\Temp\RemoveNamespaces.xslt";
   const string OUTPUTXMLFILE = @"e:\temp\UniversalShipment_output.xml";

   try
   {
      XsltArgumentList xslArg = new XsltArgumentList();

      using (XmlReader src = XmlReader.Create(SOURCEXMLFILE))
      {
         XslCompiledTransform xslt = new XslCompiledTransform();
         xslt.Load(XSLTFILE, new XsltSettings(true, true), new XmlUrlResolver());

         XmlWriterSettings settings = xslt.OutputSettings.Clone();
         settings.IndentChars = "\t";
         // to remove BOM
         settings.Encoding = new UTF8Encoding(false);

         using (XmlWriter result = XmlWriter.Create(OUTPUTXMLFILE, settings))
         {
            xslt.Transform(src, xslArg, result, new XmlUrlResolver());
            result.Close();
         }
      }
      Console.WriteLine("File '{0}' has been generated.", OUTPUTXMLFILE);
   }
   catch (Exception ex)
   {
      Console.WriteLine(ex.Message);
   }
}
🌐
GitHub
gist.github.com › BlueReZZ › 1570129
Strip all namespaces from XML Document in C# · GitHub
Strip all namespaces from XML Document in C#. GitHub Gist: instantly share code, notes, and snippets.
🌐
GitHub
github.com › dotnet › sdk › issues › 16869
How to remove System.Xml.XmlElement (not XElement) Outerxml xmlns? · Issue #16869 · dotnet/sdk
March 5, 2021 - void Main() { var doc = new XmlDocument(); doc.LoadXml(xml); XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable); ns.AddNamespace("x", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); var dimension = doc.SelectSingleNode("/x:worksheet/x:dimension",ns) as XmlElement ; ns.RemoveNamespace("x","http://schemas.openxmlformats.org/spreadsheetml/2006/main"); Console.WriteLine(dimension.OuterXml); //<dimension ref="A1:B6" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" /> dimension.RemoveAttributeNode("xmlns",dimension.NamespaceURI); Console.WriteLine(dimension.OuterXml); //<dimension ref="A1:B6" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" /> dimension.RemoveAttribute("xmlns"); Console.WriteLine(dimension.OuterXml); //<dimension ref="A1:B6" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" /> }
Author   shps951023
🌐
Microsoft
social.msdn.microsoft.com › Forums › vstudio › en-US › 8e15a247-92fd-46de-b3be-90b3d4d95a7c › how-to-remove-xml-namespace-prefixes-in-c
How to remove xml namespace prefixes in c# | Microsoft Learn
November 8, 2021 - Here's how to remove the namespaces themselves (from code posted here). var doc = XDocument.Load("Test.xml"); var namespaces = from a in doc.Descendants().Attributes() where a.IsNamespaceDeclaration && a.Name != "xsi" select a; namespaces.Remove(); doc.Save("Test_New.xml");
Find elsewhere
Top answer
1 of 2
42

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

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

Here's the code:

Copyusing System;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        XDocument doc = XDocument.Load("test.xml");
        // All elements with an empty namespace...
        foreach (var node in doc.Root.Descendants()
                                .Where(n => n.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(...)
    }
}
2 of 2
23

There is no need to 'remove' the empty xmlns attribute. The whole reason that the empty xmlns attrib is added is because the namespace of your childnodes is empty (= '') and therefore differ from your root node. Adding the same namespace to your childs as well will solve this 'side-effect'.

CopyXNamespace xmlns = XNamespace.Get("http://my.namespace");

// wrong
var doc = new XElement(xmlns + "Root", new XElement("Firstelement"));

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

// right
var doc = new XElement(xmlns + "Root", new XElement(xmlns + "Firstelement"));

// gives:
<Root xmlns="http://my.namespace">
    <Firstelement />
</Root>
Top answer
1 of 3
14

I'd like to expand upon the existing answers. Specifically, I'd like to refer to a common use-case for removing namespaces from an XElement, which is: to be able to use Linq queries in the usual way.

When a tag contains a namespace, one has to use this namespace as an XNamespace on every Linq query (as explained in this answer), so that with the OP's xml, it would be:

XNamespace ns = "http://www.blablabla.com/bla";
var element = xelement.Descendants(ns + "retEvent")).Single();

But usually, we don't want to use this namespace every time. So we need to remove it.

Now, @octaviocc's suggestion does remove the namespace attribute from a given element. However, the element name still contains that namespace, so that the usual Linq queries won't work.

Console.WriteLine(xelement.Attributes().Count()); // prints 1
xelement.Attributes().Where( e => e.IsNamespaceDeclaration).Remove();
Console.WriteLine(xelement.Attributes().Count()); // prints 0
Console.WriteLine(xelement.Name.Namespace); // prints "http://www.blablabla.com/bla"
XNamespace ns = "http://www.blablabla.com/bla";
var element1 = xelement.Descendants(ns + "retEvent")).SingleOrDefault(); // works
var element2 = xelement.Descendants("retEvent")).SingleOrDefault();      // returns null

Thus, we need to use @Sam Shiles suggestion, but it can be simplified (no need for recursion):

private static void RemoveAllNamespaces(XElement xElement)
{
    foreach (var node in xElement.DescendantsAndSelf())
    {
        node.Name = node.Name.LocalName;
    }
}

And if one needs to use an XDocument:

private static void RemoveAllNamespaces(XDocument xDoc)
{
    foreach (var node in xDoc.Root.DescendantsAndSelf())
    {
        node.Name = node.Name.LocalName;
    }
}

And now it works:

var element = xelement.Descendants("retEvent")).SingleOrDefault();
2 of 3
11

@octaviocc's 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);
            }
        }
    } 
🌐
Post.Byes
post.bytes.com › home › forum › topic › c sharp
How to remove xmlns attribute from XML document (.net) - Post.Byes
May 6, 2006 - However, in our particular case, the data files (in XML) are generated by someone else. That particular namespace may mean something to them but nothing to us. As I mentioned in my previous post, if I manually removed 'xmlns="the-namespace"' from the XML data file, my program could parse and load the data to the XmlDataDocument object without any problem.
🌐
ASP.NET Forums
forums.asp.net › t › 2115702.aspx
How to remove xmlns tag from xml element using c# | The ASP.NET Forums
February 16, 2017 - Book myBook = new Book(); myBook.TITLE = "A Book Title"; Price myPrice = new Price(); myPrice.price = (decimal)9.95; myPrice.currency = "US Dollar"; myBook.PRICE = myPrice; Books myBooks = new Books(); myBooks.Book = myBook; mySerializer.Serialize(myWriter, myBooks, myNamespaces); myWriter.Close(); } } public class Books { public Book Book; } public class Book { public string TITLE; public Price PRICE; } public class Price { public decimal price { get; set; } public string currency { get; set; } } ... <?xml version="1.0" encoding="utf-8"?> <Books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Book> <TITLE>A Book Title</TITLE> <PRICE> <price>9.95</price> <currency>US Dollar</currency> </PRICE> </Book> </Books>
🌐
Microsoft Learn
learn.microsoft.com › en-us › archive › msdn-technet-forums › 1109989a-f834-4e1d-a32c-1adc7baf7942
How to remove xmlns tag from xml element using c# | Microsoft Learn
Book myBook = new Book(); myBook.TITLE = "A Book Title"; Price myPrice = new Price(); myPrice.price = (decimal)9.95; myPrice.currency = "US Dollar"; myBook.PRICE = myPrice; Books myBooks = new Books(); myBooks.Book = myBook; mySerializer.Serialize(myWriter, myBooks, myNamespaces); myWriter.Close(); } } public class Books { public Book Book; } public class Book { public string TITLE; public Price PRICE; } public class Price { public decimal price { get; set; } public string currency { get; set; } } ... <?xml version="1.0" encoding="utf-8"?> <Books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Book> <TITLE>A Book Title</TITLE> <PRICE> <price>9.95</price> <currency>US Dollar</currency> </PRICE> </Book> </Books>
🌐
Webdevtutor
webdevtutor.net › blog › c-sharp-xml-serialization-remove-xmlns
Removing xmlns Attribute from XML Serialization in C#
One approach to remove the xmlns attribute during XML serialization is by using the XmlSerializerNamespaces class. This class allows you to specify the namespaces to be excluded from the output XML.
🌐
Oxygen XML
oxygenxml.com › home › board index › general xml questions
How to Remove xml nodes namespaces and prefixes using c# - Oxygen XML Forum
October 11, 2017 - cobie/core" core:externalID="3eM8WbY_59RR5TDWry5aRU" xmlns:core="http://docs.buildingsmartalliance.org/n ... cobie/core" xmlns:cobielite="http://docs.buildingsmartalliance.org/n ... /cobielite" core:externalEntityName="IfcBuilding" core:externalSystemName="Autodesk Revit Architecture 2011" xsi:schemaLocation="http://docs.buildingsmartalliance.org/n ... /cobielite cobielite.xsd"> <FacilityName>PN 0001</FacilityName> <FacilityCategory>11-13 24 14: Clinic</FacilityCategory> <ProjectAssignment core:externalEntityName="IfcProject" core:externalID="3eM8WbY_59RR5TDWry5aRV" core:externalSystemName="Au
🌐
Webdevtutor
webdevtutor.net › blog › c-sharp-xml-remove-xmlns-attribute
A Guide to Removing xmlns Attribute in C# XML Processing
In C#, you can achieve this by utilizing the XmlDocument class provided by the .NET framework. Below is a simple example demonstrating how you can remove the xmlns attribute from an XML document: