简体   繁体   中英

Trying to move data from XML to an Excel spreadsheet

I'm trying to learn how to use PowerShell to speed up some tasks at work.

My goal is to take an XML document that lists some data about a product, and take the data from a certain recurring subnode and place it into a new row in Excel.

So the XML might look something like this (including the "sequence" attribute):

<xml>  
  <tracks> 
    <track sequence="1"> 
      <tracktitle>StuffIWant</tracktitle>
    </track>
    <track sequence="2">
      <tracktitle>StuffIWant2</tracktitle>
    </track>
    <track sequence="3">
      <tracktitle>StuffIWant3</tracktitle>
    </track>
  </tracks>
</xml> 

And I want to take each tracktitle and place it in a row in excel.

I'm at the point where I can place one specific thing in Excel, like a single entity such as xml.artist.artistname , but if I want to loop the process to grab all the tracks then I don't know how to properly write the loop. I've tried a bunch of different things, but here's the thing that makes the most sense in my head ( $books is the XML document I'm working with):

$row = 5
foreach ($track in $books.tracks) {
  $track = $books.tracks.track.tracktitle
  $excelworksheet.cells.item($row, 2) = $track
  $row++
}
  • You need to access the track -property in the xml to actually get the array of track-elements. tracks is a single node, while it contains multiple track -elements (that you can access as an array).
  • You're not using the current item $track inside your loop.
  • $books.tracks isn't valid with the included sample. You're missing the xml root-element

Try this:

$row = 5
foreach ($track in $books.xml.tracks.track) {
    $title = $track.tracktitle
    $excelworksheet.cells.item($row, 2) = $title
    $row++
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM