Friday, January 3, 2014

The .NET way of changing a namespace within an XML Document

I'm on a project which receives messages and 'normalizes' the namespace of the XML message. You can do this easily in BizTalk by using the ESB pipeline components (ESB Add Namespace and ESB Remove Namespace).

If you aren't using BizTalk, you can do this in .NET as well, using the RemoveAttribute and SetAttribute methods. You may also wish to attempt the NamespaceURI.Replace method as well.

If you look closely at the documentation for the RemoveAttribute and SetAttribute link, at the bottom you will see
Therefore, changing xmlns attributes will have no affect until you save and reload the XmlDocument object.
Put a trace or watch in the Locals viewer and step through within Visual Studio debug mode. You will find out quickly that the xml document doesn't change if you try to modify the XmlDocument directly in code.

The way to accomplish this is by creating a placeholder XmlDocument variable, copy the contents of the original XmlDocument, and at then replace the namespace.  This can be done with a few lines of code: