powershell - 从特定的XML字段中检索值

标签 powershell xpath

我有一个从Invoke-RestMethod收到的xml文件:

$request = Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -ContentType $contentType -Body $body

XML:
<Body>
  <Response>
    <result>
      <resources>
        <resource>
          <id>012345</id>
          <rev>
            <value>x1</value>
            <ignore>false</ignore>
          </rev>
          <type>
            <value>Zw379E01-2362-48A3</value>
          </type>
          <attributes>
            <attribute>
              <id>
                <value>1B2C-3D4E-5G6H</value>
              </id>
              <name>ID</name>
              <values>
                <value>5B3CD8E2-746A-54993</value>
              </values>
            </attribute>
            <attribute>
              <id>
                <value>77BB84E18-F048-350CCC-E040</value>
              </id>
              <name>Updated</name>
              <values>
                <value>08.2019</value>
              </values>
            </attribute>
            <attribute>
              <id>
                <value>1111-2222-3333</value>
              </id>
              <name>Name</name>
              <values>
                <value>TEST</value>
              </values>
            </attribute>
          </attributes>
        </resource>
        <resource>
        ...
        </resource>
        <resource>
        ...
        </resource>
      </resources>
    </result>
  </Response>
</Body>

有几个“资源”块。
我需要在attribute.attribute.values.value = TEST的条件下提取“id”(Body.Response.result.resources.resource.id)

我可以通过以下方式提取“id”的所有值:
$request.SelectNodes("//id")

但是我无法按照以下示例进行过滤:
$request.SelectNodes("//id") | ?{$_./attributes/attribute/values/value -eq "TEST"}

我将不胜感激任何帮助。谢谢!

最佳答案

您要在此处选择的是resource节点,其中attributes节包含值= attribute"TEST",然后从所述资源中获取ID。内部选择子句进入XPath过滤器中的[]中:

$request.SelectNodes('//resource[attributes/attribute/values/value[. = "TEST"]]').id

关于powershell - 从特定的XML字段中检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57375284/

相关文章:

invoke-sqlcmd 的 Powershell 进度条

css - 需要有关 xpath 或 css : clicking common popup. gif 的所有表数据元素的帮助,例如 "One"、 "two"

html - 如何选择 XPath 中具有特定类的最后一个 XHTML <span> 元素?

powershell - PowerShell字符串格式在函数内的不同行为

regex - 使用正则表达式拆分从IP地址中删除第一个八位位组

PowerShell: `$matches` 是否保证与管道变量同步执行管道?

xml - 将 XML 扁平化为 HTML 表

powershell - 如何从Powershell输出中删除属性 namespace ?

xml - 如何使用 xmlAttrs 制作长度节点的 xpathSApply 输出向量?

Java XPath "if"语句