如何在PowerShell 3中将xml写入CSV文件?

时间:2014-05-01 10:19:42

标签: xml powershell csv

我有以下需要写入powershell 3中的csv文件的XML代码(大量减少)。底部的powershell代码是我得到了多远,它可以将整个XML文档写入控制台,但不会将xml写入csv。

xml

<?xml version="1.0" encoding="utf-8"?>
<DataReport>
    <ApiKeyId>1521</ApiKeyId>
    <Timestamp>2014-05-01 11-06-42</Timestamp>
<DataReportContent>
<Row><RowTypeCode RowTypeId="3297" Label="The University of Edinburgh">10007790</RowTypeCode>
    <Year Id="10" Label="2009/10" />
    <Value ValueTypeId="3517-3508">9592</Value><FieldCode FieldId="4502" Label="Undergraduate">2</FieldCode>
    <FieldCode FieldId="6271" Label="Female">2</FieldCode>
</Row>
</DataReportContent>
</DataReport>

powershell

[xml]$Xmlvar = Get-Content C:\Users\dantrobus\documents\csvfile.csv
$rows = $Xmlvar.DataReport.DataReportContent.row
foreach ($row in $rows)
{
     write-host $row.RowTypeCode,$row.year,$row.FieldCode
     Export-Csv -path C:\Users\dantrobus\documents\csvfile.csv -InputObject $row.RowTypeCode,$row.year,$row.FieldCode -append
}  

1 个答案:

答案 0 :(得分:0)

试试这个:

foreach ($row in $rows)
{
    # next line is for debug only, so you can see what's being processed
    # in the console window
    $row.RowTypeCode,$row.year,$row.FieldCode 

    # this line pipes the objects for processing
    $row.RowTypeCode,$row.year,$row.FieldCode |
    Export-Csv -path C:\Users\dantrobus\documents\csvfile.csv -append -NoTypeInformation
}