2

我正在尝试使用 powershell 解析一个 vcxproj 文件(实际上是使用 .NET 类 System.Xml.XmlDocument)。该问题似乎与根元素的 xmlns 属性有关 - 请参阅下面的示例 xml 文件(原始 xml 的摘录)

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup Label="ProjectConfigurations">
    <ProjectConfiguration Include="Debug|Win32">
      <Configuration>Debug</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|Win32">
      <Configuration>Release</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
  </ItemGroup>
</Project>

使用 powershell 我打开 xml 文件并想要选择一些节点。但这实际上并没有返回任何节点。

[System.Xml.XmlDocument] $xml = new-object System.Xml.XmlDocument
$xml.Load("/path/to/xml/file")
$nodes = $xml.SelectNodes("//ProjectConfiguration")

我已经尝试添加一个命名空间管理器,但这并没有帮助:

[System.Xml.XmlDocument] $xml = new-object System.Xml.XmlDocument
$xml.Load("/path/to/xml/file")
$mgr=new-object System.Xml.XmlNamespaceManager($xml.Psbase.NameTable)
$mgr.AddNamespace("gr",$xml.configuration.psbase.NamespaceURI)
$nodes = $xml.SelectNodes("//ProjectConfiguration")

如果我删除根元素的 xmlns 属性,一切正常。

问候,约翰内斯

4

1 回答 1

3

我在这里找到了一个适用于此 PowerShell的 C# 示例:

$inputstring = @'
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup Label="ProjectConfigurations">
    <ProjectConfiguration Include="Debug|Win32">
      <Configuration>Debug</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|Win32">
      <Configuration>Release</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
  </ItemGroup>
</Project>
'@
$xpath = "/rs:Project/rs:ItemGroup/rs:ProjectConfiguration"
$xmldoc = New-Object System.Xml.XmlDocument
$xmldoc.LoadXml($inputstring)
# !!USE xmldoc.load if you want to load from a file instead

# Create an XmlNamespaceManager for resolving namespaces
$nsmgr = New-Object System.Xml.XmlNamespaceManager($xmldoc.NameTable);
$nsmgr.AddNamespace("rs", "http://schemas.microsoft.com/developer/msbuild/2003");

$root = $xmldoc.DocumentElement
$nodes = $root.SelectNodes($xpath, $nsmgr)

$outputstring = "Found " + $nodes.Count + " item(s)"
write-host $outputstring

我得到的输出是:

Found 2 item(s)
于 2012-07-19T12:30:44.387 回答