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:\MyApplication\Configuration.xml that stores configuration for your application. Itlook like the sample below.
<?xml version="1.0" encoding="utf-8" standalone="yes"?>server01 server02.domain.local 25
The code - C#
First up, let's look at the C# code to read the value of the "BackupServer" key from the file above.
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
Dim document As XPathDocument = New XPathDocument("C:\MyApplication\Configuration.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. :)
Played