XmlLists with Psake / Powershell

On a POSH roll here, this time I needed to list out the Include attributes for references in an msbuild file. Let’s take a look at the POSH script equivalent of XmlList:

function xmlList([string]$file, [string]$xpath, [hashtable]$namespaces) { 
    [xml] $fileXml = Get-Content $file 
    $xmlNameTable = new-object System.Xml.NameTable
    $xmlNameSpace = new-object System.Xml.XmlNamespaceManager($xmlNameTable)

    foreach($key in $namespaces.keys)
    {
        $xmlNameSpace.AddNamespace($key, $namespaces.$key);
    }
    $nodes = @()
    $node = $fileXml.SelectNodes($xpath, $xmlNameSpace) 
    $node | ForEach-Object { $nodes += @($_.Value)}
    
    return $nodes
}

Now to use this we can do this:

$namespaces = @{ "xsi" = "http://schemas.microsoft.com/developer/msbuild/2003"}
$xpath = "//xsi:Reference/xsi:HintPath/../@Include"

$nodes = xmlList "$examplesdest_dir\NBehave.Examples.csproj" $xpath $namespaces

And it gives us a list of the references in the msbuild file.

image

blog comments powered by Disqus