Have you ever needed to query a specific key value in an XML file? Depending on the format of your XML file, here’s how to do it using XPathNavigator.

This is something I planned to write about ages ago but never got around to it.

Configuration

The System.Xml.XPath Namespace has some pretty useful stuff in it. This article is going to cover how to use both VB.NET and C# to extract a particular key value from an XML file. Let’s say you have a simple XML file called C:MyApplicationConfiguration.xml that stores configuration for your application. It looks like the sample below.

Configuration.xml:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<My.Application.Config>
  <Settings>
     <BackupServer>server01</BackupServer>
     <SmtpServer>server02.domain.local</SmtpServer>
     <SmtpPort>25</SmtpPort>
  </Settings>
</My.Application.Config>

The code – C#

First up, let’s look at the C# code to read the value of the "BackupServer" key from the file above.

Read a key using C#”:

XPathDocument document = new XPathDocument("C:\MyApplication\Configuration.xml");
XPathNavigator navigator = document.CreateNavigator();

XPathNavigator currentNode = navigator.SelectSingleNode("//My.Application.Config/Settings/BackupServer");
String backupServer = currentNode.InnerXml.ToString();

The code – VB.NET

Read a key using VB.NET:

Dim document As XPathDocument = New XPathDocument("C:MyApplicationConfiguration.xml")
Dim navigator As XPathNavigator = document.CreateNavigator()

Dim currentNode As XPathNavigator =
navigator.SelectSingleNode("//My.Application.Config/Settings/BackupServer")
Dim backupServer As String = currentNode.InnerXml.ToString()

That’s it! Pretty simple really. 🙂