Monday, April 20, 2009

Avoid Default Namespace on Configuration File

For example, we has configuration file like this:

  1: <?xml version="1.0"?>
  2: <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  3: <appSettings>
  4:  <add key="CommandTimeout" value="60"/>
  5: ...
Now, we try to read some node with specified xpath (ex: appSettings). The codes like below:
  1: string configurationFileName = ""; // -> fill with full path of configuration file.
  2: XmlDocument xmlDocument = new XmlDocument();
  3:
  4: try { xmlDocument.Load(configurationFileName); }
  5: catch (XmlException ex) { throw ex; }
  6:
  7: string xPath = "/configuration/appSettings";
  8: XmlNode xmlNode = xmlDocument.SelectSingleNode(xPath);
I found that this code doesn't work with VS 2005 (SelectSingleNode returns null) because configuration element has xmlns: <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> .

I was able to delete xmlns attribute without any visible side effects to make SelectSingleNode working .

But it will be probably required to use new classes in Configuration namespace or use XmlNamespaceManager.
The codes like below:

  1: string configurationFileName = ""; // -> fill with full path of configuration file.
  2: XmlDocument xmlDocument = new XmlDocument();
  3:
  4: try { xmlDocument.Load(configurationFileName); }
  5: catch (XmlException ex) { throw ex; }
  6:
  7: string xPath = "/configuration/appSettings";
  8:           
  9: XmlNamespaceManager xmlNamespaceManager = null;
 10: XmlAttribute xmlnsAttribute = xmlDocument.DocumentElement.Attributes["xmlns"];
 11: if (xmlnsAttribute != null)
 12: {
 13:      string prefix = "ronaldNS";
 14:      xmlNamespaceManager = new XmlNamespaceManager(xmlDocument.NameTable);
 15:      xmlNamespaceManager.AddNamespace(prefix, xmlnsAttribute.Value);
 16:
 17:      //Re-configure xPath with included the prefix
 18:      prefix = String.Concat("/", prefix, ":");
 19:      xPath = xPath.Replace("/", prefix);
 20: }
 21: XmlNode xmlNode = xmlDocument.SelectSingleNode(xPath, xmlNamespaceManager);
Above codes will work fine with configuration file has or not the xmlns attribute.

Have fun!

No comments:

Post a Comment