我有以下的PowerShell函数:
function getProjReferences([string] $projFile) {
# Returns nothing
$Namespace = @{ ns = "http://schemas.microsoft.com/developer/msbuild/2003"; };
$Xml = Select-Xml -Path $projFile -Namespace $Namespace -XPath "//ns:Project/ItemGroup/Reference"
# Returns nothing
[xml] $xml = Get-Content -Path $projFile
[System.Xml.XmlNamespaceManager] $nsMgr = New-Object -TypeName System.Xml.XmlNamespaceManager($xml.NameTable)
$nsMgr.AddNamespace("ns", "http://schemas.microsoft.com/developer/msbuild/2003");
[XmlNode] $nodes = $xml.SelectNodes("/ns:Project/ItemGroup/Reference", $nsMgr);
}
尽管XPath查询是完全有效的,但两次尝试都没有返回任何内容。我已经尝试在xml中删除默认命名空间xmlns="http://schemas.microsoft.com/developer/msbuild/2003",这样可以正常工作。
我知道我必须将默认命名空间映射到URI,并使用此映射来查询XML,但似乎无法使其工作。
如何使用默认命名空间查询XML?我还没有在Google上找到任何可用的信息。
更新
工作代码:
function getProjReferences([string] $projFile) {
[xml] $xml = Get-Content -Path $projFile
[System.Xml.XmlNamespaceManager] $nsMgr = New-Object -TypeName System.Xml.XmlNamespaceManager($xml.NameTable)
$nsMgr.AddNamespace("ns", "http://schemas.microsoft.com/developer/msbuild/2003");
[XmlNode] $nodes = $xml.SelectNodes("/ns:Project/ns:ItemGroup/ns:Reference", $nsMgr);
}