2

我不是 PowerShell 或 XPath 方面的专家,但我正在努力解决这个看似简单的问题。假设我有这个 XML 文档:

<?xml version="1.0" encoding="utf-8"?>
<Cars>
  <Car>
    <Name>Car1</Name>
    <Colors>
      <Color>
        <Name>Indian yellow</Name>
        <Effects>
          <Effect>Blur</Effect>
          <Effect>Shadow</Effect>
        </Effects>
      </Color>
      <Color>
        <Name>Fireapple red</Name>
        <Effects>
          <Effect>Shadow</Effect>
        </Effects>
      </Color>
    </Colors>
  </Car>
  <Car>
    <Name>Car2</Name>
    <Colors>
      <Color>
        <Name>Indian yellow</Name>
        <Effects>
          <Effect>Blur</Effect>
          <Effect>Shadow</Effect>
          <Effect>Saturated</Effect>
        </Effects>
      </Color>
      <Color>
        <Name>Chrome black</Name>
        <Effects>
          <Effect>Saturated</Effect>
        </Effects>
      </Color>
    </Colors>
  </Car>
  <Car>
    <Name>Car3</Name>
    <Colors>
      <Color>
        <Name>Indian yellow</Name>
        <Effects>
          <Effect>Shadow</Effect>
          <Effect>Saturated</Effect>
        </Effects>
      </Color>
      <Color>
        <Name>Fireapple red</Name>
        <Effects>
          <Effect>Saturated</Effect>
        </Effects>
      </Color>
    </Colors>
  </Car>
</Cars>

如何使用 Select-Xml 选择具有“饱和”颜色效果的汽车名称?请注意,我需要一个独特的汽车集合,例如 Car2 不能选择两次,即使两种颜色都具有“饱和”效果。

4

3 回答 3

1

XPath/Cars/Car[Colors/Color/Effects/Effect = 'Saturated']/Name应该可以。

于 2013-01-16T14:20:44.717 回答
1

使用

/*/Car[Colors/Color/Effects/Effect = 'Saturated'
     and
       not(Name = preceding-sibling::Car[Colors/Color/Effects/Effect = 'Saturated']/Name)
      ]
于 2013-01-16T14:21:09.283 回答
0

我正在尝试自己学习 xpath,所以这可能并不完美,但您可以尝试:

$xml = [xml] (Get-Content C:\test.xml)
$names = $xml.SelectNodes('/Cars/Car[Colors/Color/Effects/Effect="Saturated"]') | Select-Object -ExpandProperty Name

或者Select-XML按照您的要求使用,请改用:

$names = Select-Xml -Xml $xml -XPath '/Cars/Car[Colors/Color/Effects/Effect="Saturated"]/Name') | Select-Object -ExpandProperty Node | Select-Object -ExpandProperty '#text'

它将名称作为字符串提取到$names变量中。

于 2013-01-16T14:21:40.000 回答