Skip to content

Instantly share code, notes, and snippets.

@KoalaBear84
Created November 7, 2018 22:58
Show Gist options
  • Save KoalaBear84/ef65431e02b208dba80df884b46bb1fd to your computer and use it in GitHub Desktop.
Save KoalaBear84/ef65431e02b208dba80df884b46bb1fd to your computer and use it in GitHub Desktop.
using System.IO;
using System.Linq;
using System.Xml.Linq;
namespace Helpers
{
public class XmlHelper
{
public static string RemoveAllNamespaces(string xmlDocument)
{
XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument));
return xmlDocumentWithoutNs.ToString();
}
public static string RemoveAllNamespaces(MemoryStream memoryStream)
{
XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Load(memoryStream));
return xmlDocumentWithoutNs.ToString();
}
static XElement RemoveAllNamespaces(XElement xmlDocument)
{
foreach (XElement XE in xmlDocument.DescendantsAndSelf())
{
// Stripping the namespace by setting the name of the element to it's localname only
XE.Name = XE.Name.LocalName;
// replacing all attributes with attributes that are not namespaces and their names are set to only the localname
XE.ReplaceAttributes((from xattrib in XE.Attributes().Where(xa => !xa.IsNamespaceDeclaration) select new XAttribute(xattrib.Name.LocalName, xattrib.Value)));
}
return xmlDocument;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment