1

我有一个 Perl 脚本,它读取一个简单的.csv文件,如下所示 -

"header1","header2","header3","header4"
 "12","12-JUL-2012","Active","Processed"
 "13","11-JUL-2012","In Process","Pending"
 "32","10-JUL-2012","Active","Processed"
 "24","08-JUL-2012","Active","Processed"
 .....

目的是将其转换.csv.xml如下文件-

<ORDERS>
  <LIST_G_ROWS>
     <G_ROWS>
         <header1>12</header1>
         <header2>12-JUL-2012</header2>
         <header3>Active</header3>
         <header4>Processed</header4>
     </G_ROWS>
     <G_ROWS>
         <header1>13</header1>
         <header2>11-JUL-2012</header2>
         <header3>In Process</header3>
         <header4>Pending</header4>
     </G_ROWS>
....
....
   </LIST_G_ROWS>
</ORDERS>

我知道XML::CSVCPAN 中有可用的工具,这将使我的生活更轻松,但我想利用已经安装XML::LibXML的来创建 XML,而不是安装XML::CSV. 我能够像上面那样读取 CSV 并创建 XML 文件,没有任何问题,但是我得到了 XML 中元素的随机顺序,即如下所示。如上所示,我需要使元素(子节点)的顺序与.csv文件同步,但我不太确定如何解决这个问题。我正在使用 ahashsort()ing 哈希也没有完全解决问题。

<ORDERS>
  <LIST_G_ROWS>
     <G_ROWS>
         <header3>Active</header3>
         <header1>12</header1>
         <header4>Processed</header4>
         <header2>12-JUL-2012</header2>                          
     </G_ROWS>
 ......

等等。下面是我的 perl 代码的片段

use XML::LibXML;
use strict;

my $outcsv="/path/to/data.csv";
my $$xmlFile="/path/to/data.xml";
my $headers = 0;
my $doc = XML::LibXML::Document->new('1.0', 'UTF-8');
my $root = $doc->createElement("ORDERS");
my $list = $doc->createElement("LIST_G_ROWS");
$root->appendChild($list);

open(IN,"$outcsv") || die "can not open $outcsv:  $!\n";
while(<IN>){    
    chomp($_);
    if ($headers == 0)
    {
        $_ =~ s/^\"//g;     #remove starting (")
        $_ =~ s/\"$//g;     #remove trailing (")
        @keys = split(/\",\"/,$_);  #split per ","
        s{^\s+|\s+$}{}g foreach @keys;  #remove leading and trailing spaces from each field
        $headers = 1;       
    }
    else{   
        $_ =~ s/^\"//g;     #remove starting (")
        $_ =~ s/\"$//g;     #remove trailing (")    
        @vals = split(/\",\"/,$_);  #split per ","
        s{^\s+|\s+$}{}g foreach @vals;  #remove leading and trailing spaces from each field

        my %tags = map {$keys[$_] => $vals[$_]} (0..@keys-1);                   
        my $row  = $doc->createElement("G_ROWS");
        $list->appendChild($row);
        for my $name (keys %tags) {
            my $tag = $doc->createElement($name);
            my $value = $tags{$name};
            $tag->appendTextNode($value);               
            $row->appendChild($tag);
        }
    }
}
close(IN);

$doc->setDocumentElement($root);
open(OUT,">$xmlFile") || die "can not open $xmlFile:  $!\n";
print OUT $doc->toString();
close(OUT);
4

3 回答 3

1

你可以完全忘记%tags哈希。相反,循环遍历 的索引@keys

for my $i (0 .. @keys - 1) {
    my $key   = $keys[$i];
    my $value = $values[$i];
    my $tag   = $doc->createElement($key);
    $tag->appendTextNode($value);
    $row->appendChild($tag);
}

这样,您的密钥的顺序就会被保留。当使用散列时,排序是不确定的。

于 2012-07-31T20:28:12.307 回答
1

你的程序比它需要的要复杂得多。为了方便和可靠,您应该使用它Text::CSV来解析 CSV 文件。

下面的程序可以满足您的需要。

use strict;
use warnings;

use Text::CSV;
use XML::LibXML;

open my $csv_fh, '<', '/path/to/data.csv' or die $!;
my $csv = Text::CSV->new;
my $headers = $csv->getline($csv_fh);

my $doc = XML::LibXML::Document->new('1.0', 'UTF-8');
my $orders = $doc->createElement('ORDERS');
$doc->setDocumentElement($orders);
my $list = $orders->appendChild($doc->createElement('LIST_G_ROWS'));

while ( my $data = $csv->getline($csv_fh) ) {

  my $rows = $list->appendChild($doc->createElement('G_ROWS'));

  for my $i (0 .. $#$data) {
    $rows->appendTextChild($headers->[$i], $data->[$i]);
  }
}

print $doc->toFile('/path/to/data.xml', 1);

输出

<?xml version="1.0" encoding="UTF-8"?>
<ORDERS>
  <LIST_G_ROWS>
    <G_ROWS>
      <header1>12</header1>
      <header2>12-JUL-2012</header2>
      <header3>Active</header3>
      <header4>Processed</header4>
    </G_ROWS>
    <G_ROWS>
      <header1>13</header1>
      <header2>11-JUL-2012</header2>
      <header3>In Process</header3>
      <header4>Pending</header4>
    </G_ROWS>
    <G_ROWS>
      <header1>32</header1>
      <header2>10-JUL-2012</header2>
      <header3>Active</header3>
      <header4>Processed</header4>
    </G_ROWS>
    <G_ROWS>
      <header1>24</header1>
      <header2>08-JUL-2012</header2>
      <header3>Active</header3>
      <header4>Processed</header4>
    </G_ROWS>
  </LIST_G_ROWS>
</ORDERS>

更新

如果没有Text::CSV提供的奇异选项,如果它的选项是固定的,它的功能就相当简单。此替代方法提供了一个子例程csv_readline来替换该Text::CSV方法readline。它的工作方式大多与模块相同。

该程序的输出与上述相同。

use strict;
use warnings;

use XML::LibXML;

open my $csv_fh, '<', '/path/to/data.csv' or die $!;

my $doc = XML::LibXML::Document->new('1.0', 'UTF-8');
my $orders = $doc->createElement('ORDERS');
$doc->setDocumentElement($orders);
my $list = $orders->appendChild($doc->createElement('LIST_G_ROWS'));

my $headers = csv_getline($csv_fh);

while ( my $data = csv_getline($csv_fh) ) {

  my $rows = $list->appendChild($doc->createElement('G_ROWS'));

  for my $i (0 .. $#$data) {
    $rows->appendTextChild($headers->[$i], $data->[$i]);
  }
}

print $doc->toFile('/path/to/data.xml', 1);

sub csv_getline {
  my $fh = shift;
  defined (my $line = <$fh>) or return;
  $line =~ s/\s*\z/,/;
  [ map { /"(.*)"/ ? $1 : $_ } $line =~ /( " [^"]* " | [^,]* ) , /gx ];
}
于 2012-07-31T21:54:14.440 回答
-2

看起来有点XML::LibXml过头了,只需使用XML::Simple和构建将描述 XML 结构的正确哈希,而不是将其转储XMLOut到 XML 文件中

于 2012-07-31T20:28:00.770 回答