Skip to content

Instantly share code, notes, and snippets.

@stevencohn
Created January 1, 2021 19:55
Show Gist options
  • Save stevencohn/51d873be5649eb5603c61c88aa1a4e4b to your computer and use it in GitHub Desktop.
Save stevencohn/51d873be5649eb5603c61c88aa1a4e4b to your computer and use it in GitHub Desktop.
/*
* Replaces the default xmlns namesapce for the given XElement and its descendants
* with the specified target namespace
*/
private static XElement RewriteNamespace(XElement element, XNamespace ns)
{
RewriteChildNamespace(element, ns);
// cannot change ns of root element directly so must rebuild it
return new XElement(ns + element.Name.LocalName,
element.Attributes().Where(a => a.Name != "xmlns"),
element.Elements()
);
}
private static void RewriteChildNamespace(XElement element, XNamespace ns)
{
foreach (var child in element.Elements())
{
RewriteChildNamespace(child, ns);
var a = child.Attribute("xmlns");
if (a == null)
{
// change XName of element when xmlns is implicit
child.Name = ns + child.Name.LocalName;
}
else
{
// remove explicit xmlns attribute
a.Remove();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment