我想使用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
}
然而,尽管给定的csproj文件中肯定有ProjectReference元素,但脚本不会输出任何内容。以下功能正在发挥作用:
[xml]$csproj = Get-Content MyProject.csproj
foreach($l in $csproj.Project.ItemGroup.ProjectReference) { Write-Host $l.Include }
但我稍后也需要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>
问题出在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
}
(根据此答案改编)