Skip to content

Instantly share code, notes, and snippets.

@BlueReZZ
Created January 6, 2012 11:03
Show Gist options
  • Save BlueReZZ/1570129 to your computer and use it in GitHub Desktop.
Save BlueReZZ/1570129 to your computer and use it in GitHub Desktop.
Strip all namespaces from XML Document in C#
public class XmlStripper
{
public XmlNode RemoveAllNamespaces(XmlNode documentElement)
{
var xmlnsPattern = "\\s+xmlns\\s*(:\\w)?\\s*=\\s*\\\"(?<url>[^\\\"]*)\\\"";
var outerXml = documentElement.OuterXml;
var matchCol = Regex.Matches(outerXml, xmlnsPattern);
foreach (var match in matchCol)
outerXml = outerXml.Replace(match.ToString(), "");
var result = new XmlDocument();
result.LoadXml(outerXml);
return result;
}
public XmlNode Strip(XmlNode documentElement)
{
var namespaceManager = new XmlNamespaceManager(documentElement.OwnerDocument.NameTable);
foreach(var nspace in namespaceManager.GetNamespacesInScope(XmlNamespaceScope.All))
{
namespaceManager.RemoveNamespace(nspace.Key, nspace.Value);
}
return documentElement;
}
}
[TestFixture]
public class NamespaceStripperTests
{
[Test]
public void Should_strip_the_namespace_from_this_goddamn_xml()
{
var xml = new XmlDocument();
xml.LoadXml(@" <track xmlns=""http://www.digiplug.com/dsc/umgistd-1_4"">
<terms>
<terms_of_use>
<subscription_online_streaming>N</subscription_online_streaming>
</terms_of_use>
</terms>
</track>");
var expected = new XmlDocument();
expected.LoadXml(@" <track>
<terms>
<terms_of_use>
<subscription_online_streaming>N</subscription_online_streaming>
</terms_of_use>
</terms>
</track>");
var result = new XmlStripper().RemoveAllNamespaces(xml.DocumentElement);
Assert.That(result.OuterXml, Is.EqualTo(expected.OuterXml));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment