将XML导出为CSV

时间:2015-09-15 20:50:34

标签: xml excel powershell csv

我有以下代码将XML导出为CSV格式。代码只生成没有内容的空CSV文件。任何想法如何让代码工作?

SELECT P.g3e_fid,
       T2.X * 1000 AS x_coord,
       T2.Y * 1000 AS y_coord,
       T.Y AS latitude,
       T.X AS longitude
  FROM PolePoint P,
       TABLE (
          SDO_UTIL.GETVERTICES (SDO_CS.TRANSFORM (P.G3E_GEOMETRY, 8265))) T,
       TABLE (SDO_UTIL.GETVERTICES (P.G3E_GEOMETRY)) T2
 WHERE P.ltt_id = 0
   AND T.ID = T2.ID
UNION ALL
SELECT P.g3e_fid,
       T2.X * 1000 AS x_coord,
       T2.Y * 1000 AS y_coord,
       T.Y AS latitude,
       T.X AS longitude
  FROM PoleDetailPoint P,
       TABLE (
          SDO_UTIL.GETVERTICES (SDO_CS.TRANSFORM (P.G3E_GEOMETRY, 8265))) T,
       TABLE (SDO_UTIL.GETVERTICES (P.G3E_GEOMETRY)) T2
 WHERE P.ltt_id = 0
   AND T.ID = T2.ID;

以下是示例XML文件:

$in_root = "C:\Temp\xml"
$out_root = "C:\Temp\csv"

$files = Get-ChildItem -Path $in_root -File

foreach ($file in $files) {
  $xml = [xml](Get-Content -Path $file.FullName -Raw)
  $props = @{}
  foreach ($item in $xml.table.row.col) {
    $props[$item.name] = $item."#text"
  }

  [PSCustomObject]$props |
    Export-Csv -NoTypeInformation -Path (Join-Path -Path $out_root -ChildPath "$($file.BaseName).csv")
}

所需的输出只是以分号分隔的列。

1 个答案:

答案 0 :(得分:0)

首先,您的XML数据没有元素tablerowcol,因此$xml.table.row.col无法正常工作。尝试从<BookAttribute>节点的子节点创建自定义对象:

$xml.SelectNodes('//BookAttribute') | ForEach-Object {
  $o = New-Object -Type PSCustomObject
  $_.ChildNodes | ForEach-Object {
    $o | Add-Member -Type NoteProperty -Name $_.Name -Value $_.'#text'
  }
  $o
} | Export-Csv 'C:\path\to\output.csv' -Delimiter ';' -NoType