如何循环分组的XML节点

时间:2016-01-16 18:20:50

标签: xml powershell

我有一个这种格式的XML文档

<rss>
  <channel>
    <item>
      <id>1</id>
      <image>img_32.jpeg</image>
    </item>
    <item>
      <id>2</id>
      <image>img_42.jpeg</image>
    </item>
    <item>
      <id>1</id>
      <image>img_52.jpeg</image>
    </item>
    <item>
      <id>3</id>
      <image>img_62.jpeg</image>
    </item>
    <item>
      <id>4</id>
      <image>img_72.jpeg</image>
    </item>
  </channel>
  </rss>

ID节点不是唯一的。我要使用PowerShell做的是按ID分组,然后遍历每个ID的分组项目。

ID 1 has two images
  loop through the two images
    do something with it

ID 2 has one image
  loop through the one image
    do something with it

etc..

到目前为止,我有以下内容:

[xml]$xml = (New-Object System.Net.WebClient).DownloadString("https://myfeedurl.xml")
$grouped = $xml.rss.channel.item | Group id
$grouped

返回

Count Name        Group
----- ----        -----
    2 1           {item}{item}
    1 2           {item}
    1 3           {item}
    1 4           {item}

但我无法确定如何使用此分组信息以便最终得到唯一的分组ID项列表,以便我可以轻松地遍历图像。

1 个答案:

答案 0 :(得分:5)

ssc inst labutil 返回的每个项目的Group属性包含组元素 - 您只需要一个嵌套循环:

Group-Object
相关问题