使用Powershell查找XML属性

时间:2019-06-04 12:34:09

标签: xml powershell xpath

需要找到所有作业名称,其中 job 节点的有效属性为 true ,而< strong> JobLocation 不是在Powershell中使用select -xml Country = England

<Employee>
  <job id = "123" Name = "Teacher" Valid ="True">
    <jobdetails>
      <JobLocation location="City=London,Country=England" JobType="Permanent"/>
    </jobdetails>
  </job>
  <job id = "356" Name = "Doctor" Valid ="True">
    <jobdetails>
      <JobLocation location="City=Tokyo,Country=Japan" JobType="Permanent"/>
    </jobdetails>
  </job>
  <job id = "987" Name = "Banker" Valid ="True">
    <jobdetails>
      <JobLocation location="City=Manchester,Country=England" JobType="Permanent"/>
    </jobdetails>
  </job>
</Employee>

我尝试过的XML路径

$xml ='//Employee/job[@Valid="True"]/jobdetails*[@*[contains(.,!"Country=England")]]/job/@Id'



$xml ='//Employee/job[@Valid="True"]/jobdetails*[@*[contains(.JobLocation,!"Country=England")]]/job/@Id'

2 个答案:

答案 0 :(得分:2)

XPath过滤器表达式(方括号中的文本)可以包含多个子句。要按子节点的值或属性进行过滤,只需将子节点或属性的相对路径作为第二子句包含在过滤器表达式中,然后将子句与适当的逻辑运算符连接。要按不包含特定子字符串的属性进行过滤,请使用not()contains()函数。

//Employee/job[@Valid="True" and jobdetails/JobLocation[not(contains(@location, "Country=England"))]]/@id

答案 1 :(得分:2)

非xpath方式:

[Xml]$xml = Get-Content employee.xml
$xml.employee.job | 
  Where { $_.valid -And 
    $_.jobdetails.joblocation.location -Notmatch 'england' } | 
  Select valid, @{n='Location';e={$_.jobdetails.joblocation.location}}


Valid Location
----- --------
True  City=Tokyo,Country=Japan