PowerShell XML SelectNodes无法处理XPath

D.R*_*.R. 17 xml powershell xpath powershell-4.0

我想使用PowerShell获取我的csproj文件中所有项目引用的列表.目前我有以下方法:

[xml]$csproj = Get-Content MyProject.csproj

$refs = $csproj.SelectNodes("//ProjectReference")
foreach($ref in $refs) {
  # Later on output more useful information
  Write-Host $ref.Name
}
Run Code Online (Sandbox Code Playgroud)

但是,尽管在给定的csproj文件中肯定存在ProjectReference元素,但脚本不会输出任何内容.以下是有效的:

[xml]$csproj = Get-Content MyProject.csproj
foreach($l in $csproj.Project.ItemGroup.ProjectReference) { Write-Host $l.Include }
Run Code Online (Sandbox Code Playgroud)

但是我以后也需要XPath +它为每个不包含ProjectReference的ItemGroup输出错误 - 那么如何使用SelectNodes函数使XPath工作?

示例XML(基本上任何带有项目引用的VS csproj文件都可以):

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup></ItemGroup>
  <ItemGroup>
     <ProjectReference Include="Text"></ProjectReference>
     <ProjectReference Include="Text2"></ProjectReference>
  </ItemGroup>
  <ItemGroup></ItemGroup>
</Project>
Run Code Online (Sandbox Code Playgroud)

Ian*_*rts 28

问题是http://schemas.microsoft.com/developer/msbuild/2003名称空间.您需要在XPath表达式中考虑此命名空间,因为XPath中未加前缀的元素名称是指不在命名空间中的元素.

[xml]$csproj = Get-Content MyProject.csproj
$ns = new-object Xml.XmlNamespaceManager $csproj.NameTable
$ns.AddNamespace("msb", "http://schemas.microsoft.com/developer/msbuild/2003")

$refs = $csproj.SelectNodes("//msb:ProjectReference", $ns)
foreach($ref in $refs) {
  # Later on output more useful information
  Write-Host $ref.Name
}
Run Code Online (Sandbox Code Playgroud)

(改编自这个答案)