Powershell:如何使用xpath同时按属性和内容进行过滤?

时间:2015-06-11 03:44:12

标签: xml powershell select xpath

我有这个脚本:

function f3
{
[xml]$xml = @"
<?xml version="1.0" encoding="utf-8"?>
<Book>
  <projects>
    <project name="Book1" date="2009-01-20">
      <editions>
        <edition language="English">Novel_1</edition>
        <edition language="English">my.Book1.com</edition>
        <edition language="German">Ge.Book1.Com</edition>
        <edition language="French">Fr.Book1.com</edition>
        <edition language="Polish">Pl.Book1.com</edition>
        <edition language="English">Novel_2</edition>
        <edition language="English">FairyTale</edition>
      </editions>
    </project>
  </projects>
</Book>
"@

$xml.SelectNodes("/Book/projects/editions")
}
f3

我希望选择&#34; language = English&#34;,内容要么包含&#34; Novel&#34;或等于&#34; FairyTale&#34;,所以我的预期输出是:

Novel_1
Novel_2
FairyTale

那么如何更改我的&#34; SelectNodes&#34;声明? 非常感谢!

2 个答案:

答案 0 :(得分:2)

在xpath中,您可以使用标准布尔运算符(如[RtpMember] rtt=2054713442 - 2054584926 - 127729 = 787 => 12ms [PlayCollect] (mobicents/ivr/35) Timeout expired waiting for dtmf [MGCP] tx=62 Started, message= NTFY mobicents/ivr/35@127.0.0.1:2427, call agent = localhost/127.0.0.1:2727 [MGCP] tx=62 was executed normaly [MGCP] tx=147484061 Started, message= DLCX mobicents/bridge/25@127.0.0.1:2427, call agent = localhost/127.0.0.1:2727 [MGCP] tx=147484061 was executed normaly or)组合多个布尔值:

and

或者,将/Book/*/*/*/edition[@language='English' and (.='FairyTale' or contains(.,'Novel'))] 个操作数分成两个谓词(and):

[]

对于这种情况,您可能还需要考虑使用/Book/*/*/*/edition[@language='English'][.='FairyTale' or contains(.,'Novel')] 函数而不是starts-with()来更精确。

旁注:contains()只是我缩短xpath表达式以适应一行而不必减少效率的方法(fe使用*//),您可以使用实际的元素名称代替/Book//edition

答案 1 :(得分:1)

下面的解决方案将xpath更新为editions元素,然后根据您的请求应用过滤位置。

$xml.SelectNodes("/Book/projects/project/editions/edition") `
    | Where-Object { $_.language -eq "English" } `
    | Where-Object { $_."#text" -like "*novel*" -or $_."#text" -eq "FairyTale" } `
    | Format-Table @{Expression={$_."#text"};Label="Novel"}