Search code examples
xmlpowershellxpathcsproj

List of nodes in a particular node in .csproj file with Powershell


I would like to ask some help because I'm totally lost.

I would like to check whether nodes in a particular part of the .csproj files contains proper data or not. In the xml snippet below I would like to get back the value of the "title" under the PropertyGroup belongs to "Debug|x64" profile.

csproj file snippet

<?xml version="1.0" encoding="utf-8"?>
  <Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
    <PropertyGroup>
    ...
    </PropertyGroup>
    <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
      <DebugSymbols>true</DebugSymbols>
      <OutputPath>bin\x64\Debug\</OutputPath>
      <DefineConstants>DEBUG;TRACE</DefineConstants>
      <DebugType>full</DebugType>
      <PlatformTarget>x64</PlatformTarget>
      <ErrorReport>prompt</ErrorReport>
      <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
      <!-- nuget stuff -->
      <title>Pet Project</title>
    </PropertyGroup>

Here is my powershell code:

function GetConfigPlatformNodeFromProjectFile($projectFile, $nodeIdentifier) {

    [xml] $pFile = Get-Content $projectFile
    $ns = New-Object System.Xml.XmlNamespaceManager -ArgumentList $pFile.NameTable
    $ns.AddNamespace("ns", $pFile.Project.GetAttribute("xmlns"))

    $nodes = $pFile.SelectNodes("//ns:Project/PropertyGroup[contains(@Condition,'Debug|x64')]", $ns)

    foreach($node in $nodes) {
        write-Host "node... " $node
    }
}

Problem is that the $nodes will be always 0. According to the articles here it should contains something more. The path is ok. I've checked many times. The xmlns attribute comes back properly. I think the problem is the xpath itself and the namespace, however I checked it many times by other XPath tools.

I don't know what I'm doing wrong in this case.

Thanks any help in advance!

András


Solution

  • Do you have to use xpath? Otherwise I would suggest something like this:

    $file = [xml](gc .\test.csproj)
    
    $file.Project.PropertyGroup | ? Condition -Like '*Debug|x64*' | select Title