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.

🌐
The Coding Forums
thecodingforums.com › archive › archive › xml
How to remove xmlns attribute from XML document (.net) | XML | Coding Forums
May 8, 2006 - Get the namespaceManager for all the default namespaces ///Pass the document as XMLElement public static XmlNamespaceManager GetNamespaceManager(XmlElement Element) { XmlNamespaceManager nsmgr = new XmlNamespaceManager(Element.OwnerDocument.NameTable); XmlNode node = (XmlNode)Element; RecurseNamespaces(node, nsmgr); return nsmgr; } private static void RecurseNamespaces(XmlNode node, XmlNamespaceManager nsmgr) { if (node.Attributes != null) { foreach (XmlAttribute attribute in node.Attributes) { if (attribute.Name.StartsWith(Constants.XML_NAMESPACE_PREFIX, StringComparison.CurrentCultureIgnoreC
🌐
Blogger
rprateek.blogspot.com › 2011 › 01 › how-to-remove-xmlns-namespace-from-xml.html
Blog for Programmers: How to remove xmlns namespace from xml using vb.net
January 23, 2011 - This function will help to remove all invisible characters in vb.net string Public Function Remove(ByVal str As String) As String ... How to show modal Dialog panel in asp.net? (In normal asp.net pages or in Master Child Asp.net web applications) Show only a dialog panel disabling the other part of the page by pressing a button. In this article i will show how can we use this feature... How to remove xmlns namespace from xml using vb.net ·
🌐
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");
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › standard › data › xml › changing-namespace-declarations-in-an-xml-document
Changing Namespace Declarations in an XML Document - .NET | Microsoft Learn
These are stored in the XmlDocument, so when you save the document, it can preserve the location of those attributes. Changing these attributes has no affect on the Name, NamespaceURI, and Prefix properties of other nodes already in the tree. For example, if you load the following document, then the test element has NamespaceURI 123. ... If you remove the xmlns attribute as follows, then the test element still has the NamespaceURI of 123.
🌐
GitHub
gist.github.com › BlueReZZ › 1570129
Strip all namespaces from XML Document in C# · GitHub
Strip all namespaces from XML Document in C# Raw · XmlNamespaceStripper.cs · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Bytes
bytes.com › home › forum › topic › .net
removing xmlns form xml vb.net - .NET Framework
November 5, 2015 - I need to remove them all.[/color] ... implemented in .NET you cannot simply change the namespace of a node, you would need to create a new node with the same local name but with no namespace....
Find elsewhere
🌐
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
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);
   }
}
🌐
Stack Overflow
stackoverflow.com › questions › 2281565 › removing-xml-namespaces-from-xml-serialized-output
vb.net - Removing XML Namespaces from XML Serialized Output - Stack Overflow
Dim string_writer As New StringWriter() Dim serializer As New XmlSerializer(GetType(MyClass), "") serializer.Serialize(string_writer, addr) txttest.Text = string_writer.ToString()
🌐
CodeProject
codeproject.com › Questions › 480904 › RemovingplusnamespacesplusinplusXMLs
[Solved] Removing namespaces in XMLs - CodeProject
April 12, 2022 - Free source code and tutorials for Software developers and Architects.; Updated: 23 Oct 2012
🌐
Microsoft Learn
learn.microsoft.com › en-us › archive › blogs › kaevans › removing-namespaces-in-xml-security-in-asp-net
Removing Namespaces in XML, Security in ASP.NET | Microsoft Learn
This stylesheet basically removes the namespace from the element or attribute. To transform the XML, you have to use the System.Xml.Xsl.XslTransform class. Typically this is done by providing a URL to the file, which internally creates an XPathDocument based on the contents of the file found at the URL.
🌐
PC Review
pcreview.co.uk › newsgroups › microsoft dotnet › microsoft c# .net
XML Serialization - Remove XML-instance namespace? | PC Review
March 17, 2008 - If you want to get rid of both - XML declaration and those namespace attributes you can create your XmlWriter with explicit settings (the namespace attributes were already discussed above): // source: object instance to serialize // file: target ...
🌐
Microsoft Developer Blogs
devblogs.microsoft.com › dev blogs › visual basic blog › removing duplicate namespaces in xml literals (shyam namboodiripad)
Removing duplicate namespaces in XML Literals (Shyam Namboodiripad) - Visual Basic Blog
July 5, 2024 - In VS 2010 / .NET 4.0, the LINQ to XML API provides ways to work-around this problem and generate better looking XML. You can add an ‘annotation’ to the root XElement / XDocument node that will tell the API not to emit duplicate namespaces as demonstrated in the below example. The API will then check each node as it is added and remove any unnecessary duplicate namespace declarations from the node.
Top answer
1 of 3
2

It seems (although you didn't share it) that the movies XML file uses namespaces. So I assume that somewhere in that file (probably on the root element) you will have something like xmlns="mymovieurl". The important thing to realize is that each XML element and attribute is identified by a pair of strings. The local name (Movie, DVD, VHS, ...) and the namespace URI (empty, mymovieurl, ...). In your code above, since you didn't specify a default namespace all your elements are in the empty namespace (their namespace URI is an empty string). But your XML file to which you're adding these have its elements in some non-empty namespace (mymovieurl). In order to preserve the namespace for the element you're adding the code has to inject the xmlns="" attribute which marks that element and all its children to be in the empty namespace (just like you specified it in your code).

The solution depends on what you want to achieve. I assume that you want to add the elements into the namespace the rest of the file uses.

One simple way to do that is to add Imports

That means that all elements in your code without a prefix should belong to the namespace "mymovieurl". (Just change that to whatever namespace URI you movies file is using).

2 of 3
2

The Imports works just like namespace declaration in XML. Since you didn't show us the input XML or the namespace URI you want the output XML to be in, it's impossible to show the right code.

Assuming your file uses namespace URI "mynsuri", then you need to add something like:

Imports <xmlns="mynsuri">

That will make is such that all elements in your code which don't specify a prefix will belong to the "mynsuri". That is assuming you actually want the Movie element and its children to belong to that namespace.

Maybe a little more explicit way would be to:

Imports <xmlns:movie="mynsuri">

And then in your code you would create the elements like:

<movie:Movie><movie:MovieID> ...

The namespace declarations (the xmlns:movie='' attribute) will be added to the output during serialization automatically for you.

Top answer
1 of 2
2

You need to register the prefix 'sd' using XmlNamespaceManager before you can use it in XPath query. Make sure you map the prefix to the default namespace http://g.h.i :

....
nsmgr = New XmlNamespaceManager(New XmlNameTable())
nsmgr.AddNamespace("sd", "http://g.h.i");

nodeList = xmlnode.DocumentElement.SelectNodes("/sd:ArrayOfAssessmentItemTimed/sd:AssessmentItemTimed", nsmgr)
....

XPath always treat element without prefix as an element with empty namespace, it doesn't have a notion of default namespace (only XML has), that's why you need to made up the prefix 'sd' here.

2 of 2
0

You can check How to: Declare and Use XML Namespace Prefixes for a simpler alternative.

Imports <xmlns="http://g.h.i">

and sample use:

'' Dim xDoc = System.Xml.Linq.XDocument.Load("file.xml")

Dim xDoc = <?xml version="1.0" encoding="utf-8"?>
           <ArrayOfAssessmentItemTimed xmlns:xsi="http://a.b.c/"
               xmlns:xsd="http://d.e.f" xmlns="http://g.h.i">
               <AssessmentItemTimed>
                   <License>0577HJK</License>
                   <ChassisNumber>VF1KT1RG646667276</ChassisNumber>
                   <Kilometers>90957</Kilometers>
               </AssessmentItemTimed>
               <AssessmentItemTimed>
                   <License>0918HHM</License>
                   <ChassisNumber>VF1KT1RG646272649</ChassisNumber>
                   <Kilometers>158142</Kilometers>
               </AssessmentItemTimed>
           </ArrayOfAssessmentItemTimed>

For Each x In xDoc.<ArrayOfAssessmentItemTimed>.<AssessmentItemTimed>

    MsgBox("License: " & vbTab & x.<License>.Value & vbLf &
           "Chassis: " & vbTab & x.<ChassisNumber>.Value & vbLf &
           "Kms:     " & vbTab & x.<Kilometers>.Value & vbLf)
Next