加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xml – XPath和Powershell – 默认命名空间

发布时间:2020-12-15 23:55:04 所属栏目:百科 来源:网络整理
导读:我有以下Power Shell功能: function getProjReferences([string] $projFile) { # Returns nothing $Namespace = @{ ns = "http://schemas.microsoft.com/developer/msbuild/2003"; }; $Xml = Select-Xml -Path $projFile -Namespace $Namespace -XPath "//n
我有以下Power Shell功能:
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);
}
如果不查看实际的XML文档(或其代表性示例),我无法100%确定.无论如何,这通常是由于xpath中缺少名称空间前缀使用.

请注意,在默认命名空间的情况下,不仅要声明默认命名空间的元素,还要考虑它们的所有后代在同一命名空间*中.我建议尝试以下xpath:

/ns:Project/ns:ItemGroup/ns:Reference

*:除了后代元素中的显式前缀用法,或者在后代级别中声明的其他默认命名空间(在更本地的范围内).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读