Sunday, June 19, 2011

PowerShell, XML and XPath

Some of the time, PowerShell makes picking apart an XML file nice and easy by providing properties on the XML object matching nodes; but inevitably you get to a point where there are more than one node of a given type as the child of the one you are at. So then it's time to break out the XPath.

Take a sample XML file (this one being a StyleCop settings file, being to hand, and complicated enough to be interesting):

And we want to extract the "FileHeaderMustShowCopyright" enabled property. So we can do something like this:

using PowerShell to navigate where there is no ambiguity, and XPath at each for in the road; or

or

or simply

depending how many of the steps above where we want to end up are of interest.

Post a Comment