gpt4 book ai didi

.net - 使用 System.Xml.XmlDocument 解析 vcxproj

转载 作者:行者123 更新时间:2023-12-02 23:30:39 26 4
gpt4 key购买 nike

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

问候,
约翰内斯

最佳答案

我在 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)

关于.net - 使用 System.Xml.XmlDocument 解析 vcxproj,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11556987/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com