如何根据孩子选择元素

时间:2013-01-16 14:12:53

标签: xml powershell xpath

我不是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选择例如具有色彩效果的汽车名称&#34;饱和&#34;?请注意,我需要一个独特的汽车集合,例如即使两种颜色都具有&#34;饱和&#34;也不能选择Car2两次。效果。

3 个答案:

答案 0 :(得分:1)

XPath /Cars/Car[Colors/Color/Effects/Effect = 'Saturated']/Name应该这样做。

答案 1 :(得分:1)

使用

/*/Car[Colors/Color/Effects/Effect = 'Saturated'
     and
       not(Name = preceding-sibling::Car[Colors/Color/Effects/Effect = 'Saturated']/Name)
      ]

答案 2 :(得分: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变量。