Camera Icon

Got an event that needs shooting?  I've covered multiple events for marathon-photos.com and can capture the scenes & emotions that make your event unique.

Some samples of my own work are at Digital Formula on Flickr.

Wand Icon

Do you or your business need a website but you're unsure where to start?  Get in touch now and we'll get it sorted.

I focus on usable functionality & can setup smaller sites using Wordpress within hours of the order being placed.  Magic!

Globe Icon

So, you've already got a website but need help managing it?  I can help you.

Don't worry about knowing every single detail.  I'll find out the most important stuff and work with you to reach your goal, not someone else's.

said on twitter: LOL spammers really do bank on the ignorance of their targets huh? A file with a .jpg.exe extension ... really? http://t.co/0TgobjQc

 
Short URL
Warning: This article is older than 180 days and may contain inaccurate information.  Please use the information below at your own risk.

Using XPathNavigator to query XML files

XML = useful

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. :)

» Tags: xml, query, xpath, xpathnavigator
DigitalFormula is an experiment in HTML5 and CSS3 design by Chris Rasmussen, an amateur/casual designer based in Melbourne, Australia. -37.813611 144.963056