【问题标题】:Use XPath to retrieve attribute value for specific attribute使用 XPath 检索特定属性的属性值
【发布时间】:2017-08-30 15:01:46
【问题描述】:

在 PowerShell 中,我尝试使用 XPath 检索属性的值。在下面的示例中,我想获取“hi”类别的“name”值,即“new test”。

示例代码展示:

<Report name="test" category="thisone">
  <String>test</String>
  <String>test2</String>
  <Report name="new test" category="hi">
    <String>hello</String>
    <String>hi again</String>
  </Report>
</Report>

这就是我所拥有的:

Select-Xml -XPath "//Report[@name='test']/Report" | Select name |
    Out-File "result.txt" 

我的结果是:

姓名 ----

我真的不需要指定类别属性,因为&lt;Report&gt; 标记总是紧跟在第一个&lt;Report&gt; 标记之后,所以这就是为什么我认为使用 XPath 会更容易。

【问题讨论】:

    标签: xml powershell xpath


    【解决方案1】:

    您需要先展开节点。 Select-XML 正在提供对象。如果你这样做:

    Select-Xml -Xml $XML -XPath "//Report[@name='test']/Report"
    

    你会得到

    节点:报告

    路径:输入流

    模式://报告[@name='test']/报告

    展开“节点”后,您将获得更多属性

    Select-Xml -Xml $XML -xPath "//Report[@name='test']/Report" | Select-Object –ExpandProperty “node” | select *
    

    名称:新测试

    类别:嗨

    字符串:{你好,再见}

    本地名称:报告

    ...等...等

    下面的完整概念

    [xml]$XML = @"
    <Report name="test" category="thisone">
     <String>test</String>
     <String>test2</String>
      <Report name="new test" category="hi">
      <String>hello</String>
      <String>hi again</String>
      </Report>
    </Report>
    "@
    
    Select-Xml -Xml $XML -xPath "//Report[@name='test']/Report" | Select-Object –ExpandProperty “node” | select name
    

    【讨论】:

    • 完美做到了!顺便说一句,我可以将该值放入变量中,在该语句之前添加类似 $hi = 的内容吗?我目前正在将 Out-File 用于文本文件,我看到它写入“name”和“----”然后是下面的值,我并不真正关心这两行并试图消除它们.. .
    • Select-Xml -Xml $XML -xPath "//Report[@name='test']/Report" | Select-Object –ExpandProperty “node” | foreach-object{$_.name} | Out-file "HELLO.TXT"
    • 不错!那也有效!有没有办法可以将它分配给变量?我试过了,我得到了:cmdlet Select-Xml at command pipeline position 1 为以下参数提供值:Xml[0]:
    • 我的意思是捕获该值并将其分配给一个变量,但不用担心,我已经想通了!感谢您的帮助!
    【解决方案2】:

    XPath 可以直接获取属性的值。

    (Select-Xml -Xml $XML -xPath "//Report[@name='test']/Report/@name").Node.Value
    

    (但仍需要从结果[XmlAttribute]中提取值。)

    【讨论】:

      【解决方案3】:

      这是一个非 xpath 版本:

      (get-content file.xml) -as 'xml' | foreach { $_.report.report.name }
      
      new test
      

      或另一个 xpath:

      get-content -raw file.xml | select-xml '//*[@category="hi"]/@name' | 
        % { $_.node.'#text' }
      
      new test
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-03
        • 2020-03-03
        • 2012-06-09
        • 1970-01-01
        相关资源
        最近更新 更多