use*_*448 6 xml powershell xpath
我有以下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);
}
Run Code Online (Sandbox Code Playgroud)
两次尝试都没有返回任何内容,虽然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);
}
Run Code Online (Sandbox Code Playgroud)
如果不查看实际的 XML 文档(或其代表性示例),我就无法 100% 确定。不管怎样,这通常是由于 xpath 中缺少命名空间前缀使用造成的。
请注意,在默认命名空间的情况下,不仅声明默认命名空间的元素,而且它的所有后代都被视为在同一命名空间*中。我建议尝试以下 xpath :
/ns:Project/ns:ItemGroup/ns:Reference
Run Code Online (Sandbox Code Playgroud)
*:除了在后代元素中显式使用前缀,或在后代级别(在更本地的范围内)声明的其他默认命名空间之外。