Wednesday, November 13, 2013

Read XML with PowerShell

I have found that the ability to define and read an xml file with PowerShell is very useful. Often times I will generate XML from an Excel spreadsheet to drive a PowerShell script.

For example, what if we wanted to read this xml file using PowerShell? Let’s say it was in a file named “sample.xml”
<?xml version="1.0" encoding="utf-8"?>
<albums>
  <album name="Time Out">
    <artist>The Dave Brubeck Quartet</artist>
    <released>12/14/1959</released>
  </album>
  <album name="Red Headed Stranger">
    <artist>Willie Nelson</artist>
    <released>5/1/1975</released>
  </album>
</albums>

Here’s how I access all the attributes and nodes.
    # path/file name of xml file
    $xmlfile = "sample.xml";
   
    # Read an xml file
    [xml]$musiccatalog = get-content $xmlfile;
    foreach ($album in $musiccatalog.albums.album) {
        # Display what we've read
        write-host;
        write-host -f green "   Album Name: " -nonewline;
        write-host -f yellow $album.name;
        write-host -f green "   Artist    : " -nonewline;
        write-host -f yellow $album.artist;
        write-host -f green "   Released  : " -nonewline;
        write-host -f yellow $album.released;
    }


And here is the output

   Album Name: Time Out
   Artist    : The Dave Brubeck Quartet
   Released  : 12/14/1959

   Album Name: Red Headed Stranger
   Artist    : Willie Nelson
   Released  : 5/1/1975


No comments:

Post a Comment