PowerShell XML SelectNodes 无法处理 XPath [英] PowerShell XML SelectNodes fails to process XPath

查看:55
本文介绍了PowerShell XML SelectNodes 无法处理 XPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to get a list of all project references in my csproj file using PowerShell. Currently I've the following approach:

[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 元素.以下工作正常:

However, the script does not output anything, although there certainly are ProjectReference elements in the given csproj file. The following is working:

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

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

But I need XPath later on as well + it outputs errors for each ItemGroup which does not contain a ProjectReference - so how to make XPath work using the SelectNodes function?

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

Sample XML (essentially any VS csproj file with project references will do):

<?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 中未带前缀的元素名称指的是在命名空间中的元素.

The problem is the http://schemas.microsoft.com/developer/msbuild/2003 namespace. You need to take account of this namespace in your XPath expressions, as unprefixed element names in XPath refer to elements that are not in a namespace.

[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
}

(改编自这个答案)

这篇关于PowerShell XML SelectNodes 无法处理 XPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆