2015-03-08 102 views
0

閱讀元素我有這樣的XML庫門PowerShell的 - 我怎麼從一個XML文件

<?xml version="1.0" encoding="utf-8"?> 
<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"> 
<channel> 
<title>ps read XML File</title> 
<description>Some Text</description> 
<item> 
<title>Element One</title> 
<description>Some Text to Element ONE</description> 
<guid>http://dlbmodigital.microsoft.com/webcasts/wmv/23976_Dnl_L.wmv</guid> 
</item> 
<item> 
<title>Element Two</title> 
<description>Some Text to Element TWO</description> 
<guid>http://dlbmodigital.microsoft.com/webcasts/wmv/23977_Dnl_L.wmv</guid> 
</item> 
<item> 
<title>Element Three</title> 
<description>Some Text to Element Three</description> 
<guid>http://dlbmodigital.microsoft.com/webcasts/wmv/23978_Dnl_L.wmv</guid> 
</item> 
</channel> 
</rss> 

我想趕從元素「GUID」的值。但我不知道如何。

有了這個代碼

"[xml]$xmldata = Get-Content -path C:\tmp\ps\test-ps.xml 
$xmldata.rss.channel.item" 

我看到了三個 「項目」 的元素。但我不知道如何從元素「guid」中捕捉到值(超鏈接)。

回答

0

如果你希望所有的GUID元素,那麼你可以使用XPath這樣的:

$xmldata.SelectNodes('//guid') | Select-Object -ExpandProperty "#text" 

http://dlbmodigital.microsoft.com/webcasts/wmv/23976_Dnl_L.wmv 
http://dlbmodigital.microsoft.com/webcasts/wmv/23977_Dnl_L.wmv 
http://dlbmodigital.microsoft.com/webcasts/wmv/23978_Dnl_L.wmv 
+0

感謝您使用xpath提示。我必須閱讀它是如何工作的。 我的目標是找到所有超鏈接(Element guid)並下載它。 用VB我統計guid元素的數量,然後用For循環下載(int_i到計數)。 隨着Powershell我不得不學習,如何訪問guid元素的方式。 – ral9004 2015-03-11 18:03:08

+0

然後這正是你想要的(除了下載它)。添加'| Foreach-object {#你的下載代碼}',你就完成了。但是除非你有條件去過濾一些guid元素,然而@ mtman的點源方法更清晰。我添加了這個給你一個與所有PowerShell版本兼容的不同解決方案。:-) – 2015-03-11 20:20:02

0

你可以通過簡單地引用他們遍歷所有的孩子:

$xmldata.rss.channel.item.guid 

但是,你不爲他們獲得自動完成。 (這只是巧合發生在「項目」,因爲這是也是一個函數)。

+1

僅供參考,僅適用於V3和因爲V3添加了成員​​枚舉功能,允許您在集合中的對象上「點」一個屬性,即item是一個集合。在V2中,你必須這樣做:'$ xmldata.rss.channel.item | Foreach {$ _。guid}'。 – 2015-03-08 20:59:33

+0

完美!有用。謝謝! – ral9004 2015-03-09 08:25:18

相關問題