Part of the deployment scripts I'm working on must programmatically munge .NET config files. And I want to be able to use xpath expressions to index into them, but xpath is more painful (for what I'm doing at least) when namespaces are involved.
Sometimes config files look like this:
<configuration>...</configuration>
But they often also look like this:
<configuration xmlns='...'>...</configuration>
I needed a way to strip out the namespace before doing my queries. I found a solution and thought I'd share it here. XmlElement.SetAttribute can be used to change the namespace declaration (this is some special case code in the .NET DOM for this). But the change doesn't seem to take effect right away - I had to serialize the DOM tree and reload it, then things worked nicely. Here's a little function to do this:
XmlDocument stripDocumentNamespace(XmlDocument oldDom) {
// some config files have a default namespace
// we are going to get rid of that to simplify our xpath expressions
if (oldDom.DocumentElement.NamespaceURI.Length > 0) {
oldDom.DocumentElement.SetAttribute("xmlns", "");
// must serialize and reload the DOM
// before this will actually take effect
XmlDocument newDom = new XmlDocument();
newDom.LoadXml(oldDom.OuterXml);
return newDom;
}
else return oldDom;
}
Posted
Oct 19 2005, 05:00 PM
by
keith-brown