Keith's profileKeith Hill's BlogPhotosBlogListsMore ![]() | Help |
|
January 07 Microsoft Dev Days in DenverIf you want to get some free exposure to the VS 2008 and Office technologies, sign up for Dev Days. It is coming to my local MS office (Denver) - details listed below. When: Thursday, January 31, 2008 8:30 AM - 5:00 PM January 02 XPath Expressions and PSCX's Select-XmlMoW wrote up a nice post on invoking XPATH expressions. Check it out here. Just wanted to let the PSCX users out there know that the equivalent of MoW's PS I:\PowerShell> Function invoke-XpathExpression ([xml]$xml,$expression) {
>> $xn = $xml.PSBase.CreateNavigator()
>> $xn.Evaluate($expression)
>> }
>>
PS I:\PowerShell> # Example using the function
PS I:\PowerShell>
PS I:\PowerShell> invoke-XpathExpression -xml (type gl.xml) -exp "sum(GroceryList/Item/Price)"
29.15 in PSCX would be:
Note that the PSCX cmdlet Select-Xml is oriented towards "selecting" node-sets hence the name. Unfortunately xpath expressions that don't result in node-sets will error. No worries though because PowerShell's Measure-Object cmdlet (measure alias provided by PSCX) can compute the sum easily. OK so that was a bit shorter but what's the big deal. Here's the deal. If your XML uses XML namespaces then this all gets a good bit harder to deal with yourself. Not impossible mind you. I have written a number of posts on handling XML that uses XML namespaces but with Select-Xml it is pretty simple. For instance, let's tweak the XML ever so slightly: <GroceryList xmlns="tempuri.org"> Note the default namespace declaration on the root element. Now the previous XPath expressions won't work but here is all we need to do with Select-Xml to make this work:
All we needed to do was provide the namespace and a temp prefix (ns) to use in the xpath query. Note that the -Namespace parameter will take an array of strings that match this format: "<prefix>=<namespace>". Renewed as Windows PowerShell MVP for 2008Woohoo! Just got word earlier today. I look forward to another awesome year of PowerShell adoption and just maybe v 2.0 - hopefully. |
|
|