简体   繁体   English

尝试将数据从 XML 移动到 Excel 电子表格

[英]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.我正在尝试学习如何使用 PowerShell 来加速工作中的某些任务。

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.我的目标是获取一个 XML 文档,其中列出了有关产品的一些数据,并从某个重复出现的子节点获取数据并将其放入 Excel 中的新行中。

So the XML might look something like this (including the "sequence" attribute):所以 XML 可能看起来像这样(包括“序列”属性):

<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.我想把每个tracktitle放在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.我现在可以在 Excel 中放置一个特定的东西,例如单个实体,例如xml.artist.artistname ,但是如果我想循环该过程以获取所有曲目,那么我不知道如何正确写循环。 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):我尝试了很多不同的东西,但这是我脑海中最有意义的东西( $books是我正在使用的 XML 文档):

$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.您需要访问 xml 中的track -property 才能实际获取 track-elements 数组。 tracks is a single node, while it contains multiple track -elements (that you can access as an array). tracks是单个节点,而它包含多个track元素(您可以作为数组访问)。
  • You're not using the current item $track inside your loop.您没有在循环中使用当前项目$track
  • $books.tracks isn't valid with the included sample. $books.tracks对包含的样本无效。 You're missing the xml root-element您缺少xml根元素

Try this:尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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