使用System.Xml.XmlDocument解析vcxproj

时间:2012-07-19 08:39:10

标签: .net xml powershell msbuild

我正在尝试使用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属性,一切正常。

此致 约翰内斯

1 个答案:

答案 0 :(得分:2)

我在C#here中找到了一个我适应这个PowerShell的例子:

$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)