Search code examples
xmlpowershellparsexml

Parse XML file in Powershell


I am trying to retrieve Exchange Rates from Yahoo

$browser = New-Object System.Net.WebClient
$browser.Proxy.Credentials =[System.Net.CredentialCache]::DefaultNetworkCredentials 

$url = 'http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote'
$xml = New-Object xml
$xml.Load($url)

[xml]$YahooDataDocument = $xml.InnerXml
$YahooDataDocument.List.resources.resource | format-table name,price

But I am unable to get the data as required, I only get:

Name     price
----     -----
resource      
resource      
resource      
resource      
resource      
.
.
..

Solution

  • Try this:

    $browser = New-Object System.Net.WebClient
    $browser.Proxy.Credentials =[System.Net.CredentialCache]::DefaultNetworkCredentials 
    $url = 'http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote'
    [xml]$xml = $browser.DownloadString($url)
    
    $resultset = New-Object System.Collections.ArrayList
    foreach ($quote in $xml.list.resources.resource){
        $singlequote = New-Object System.Collections.Specialized.OrderedDictionary
        foreach($element in $quote.field){
            $singlequote.Add($element.name,$element.'#text')
        }
        $resultset += New-Object PSObject -Property $singlequote
    }
    $resultset | format-table 
    

    Thing is when you are getting $xml.list.resources.resource it comes as System.Array so you need to deal with every object separately.