Skip Navigation LinksHome > View Post
Powershell to test your XPath

I'm quickly coming to the realisation that Powershell might just replace all those little 'trial and error' apps that I used to download everytime I needed one. Not too long ago I posted about how PowerShell had become my weapon of choice when playing with Regular Expressions. Earlier today a colleague contacted me for some help with an XPath query. Sure enough, powershell would have been more than up to the task.

We start by creating an XML document to play with:

$xml = [xml] '<root><node att="a">hello</node><node att="b">goodbye</node></root>'

How easy was that? And now we can

$xml.SelectNodes("/root/node")

att #text
--- -----
a hello
b goodbye

or test your predicates

$xml.SelectNodes("/root/node[@att='a']")

att #text
--- -----
a hello

I won't bore you with a million examples suffice to say you have a full XmlDocument (from System.Xml) in $xml at your disposal.

Want to load a meatier xml document from disk for your experimentation?

$xml = New-Object "System.Xml.XmlDocument"
$xml.load("c:\myfile.xml")

Very handy. If only PowerShell shipped as part of Vista... get yours here.

Josh Post By Josh Twist
4:35 AM
26 Jan 2008

Comments:

Posted by Phil Fearon @ 27 Jan 2008 10:05 AM
XPath. A great way for extracting xml config data stored as xml for a powershell script. A couple of points -

A single-line alternative to:

$xml = New-Object "System.Xml.XmlDocument"
$xml.load("c:\myfile.xml")

would be:

$xml = [xml] (get-content "c:\myfile.xml")

Also, one thing that threw me at first was that the returned XmlNode(s) is 'wrapped' by PowerShell. So, to access basic properties of XmlNode, I had to use the 'PSBase' member as in:

$value = $node.psbase.innertext


Post a comment:

Name  

E-mail (never shared)

URL

Comments  

Captcha ImageRefresh Image
What's this?
Enter code above