代码之家  ›  专栏  ›  技术社区  ›  Ian Kemp

如何从SelectXml调用本机XPath函数?

  •  0
  • Ian Kemp  · 技术社区  · 3 月前

    使用PowerShell Core 7.4.6。

    给定文件 /path/to/file.csproj

    <Project Sdk="Microsoft.NET.Sdk">
        <ItemGroup>
            <ProjectReference Include="Path\To\Something.csproj" />
        </ItemGroup>
    </Project>
    

    我希望以下代码段将选择 ProjectReference 使用内置XPath从该文件中提取节点 ends-with 功能

    select-xml -path "/path/to/file.csproj" `
        -xpath "/Project/ItemGroup/ProjectReference[ends-with(@Include, 'Something.csproj')]"
    

    但相反,它会产生错误

    Select-Xml: Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.
    

    如果我尝试使用XPath函数名称空间显式地限定其范围

    select-xml -path "/path/to/file.csproj" `
        -xpath "/Project/ItemGroup/ProjectReference[fn:ends-with(@Include, 'Something.csproj')]" `
        -namespace @{ "fn" = "http://www.w3.org/2005/xpath-functions" }
    

    我得到了一个不同的错误

    Select-Xml: XsltContext is needed for this query because of an unknown function.
    

    我错过了什么? The documentation for Select-Xml 没有提到对调用XPath函数的限制,因此我假设它们是本机支持的。

    1 回复  |  直到 3 月前
        1
  •  2
  •   Mathias R. Jessen    3 月前

    中内置的XPath支持。NET仅涵盖XPath 1.0/1.1版本指定的函数 ends-with 在XPath版本2之前,它不是XPath的一部分。

    您可以使用 substring / string-length 剪下绳子的尾部,然后寻找:

    $tailValue = 'Something.csproject'
    $xPathEndsWithExpression = "/Project/ItemGroup/ProjectReference[substring(@Include, string-length(@Include) - $($tailValue.Length - 1)) = '${tailValue}')]"
    
    Select-Xml -Path "/path/to/file.csproj" -XPath $xPathEndsWithExpression