Created
January 1, 2021 19:55
-
-
Save stevencohn/51d873be5649eb5603c61c88aa1a4e4b to your computer and use it in GitHub Desktop.
This file contains 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.
Learn more about bidirectional Unicode characters
/* | |
* 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