2016-01-16 73 views
2

我這種格式如何通過分組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節點不是唯一有一個XML文檔循環。我想使用PowerShell進行分組,然後循環遍歷每個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項目,所以我可以輕鬆地循環瀏覽圖像。

回答

5

通過Group-Object返回的每個項目的Group屬性包含組元素 - 所有你需要的是一個嵌套循環:

foreach($group in $grouped) 
{ 
    "Processing images with id $($group.Name)" 
    foreach($image in $group.Group) 
    { 
    "Processing $($image.Name)" 
    } 
} 
+0

這是完美的 - 感謝馬蒂亞斯! – norbert