perl - 解析/生成xml

阅读更多
原始的方法

test.xml


   
   




test.pl
use XML::Simple;
my $xml   = new XML::Simple;
my $data = $xml->XMLin("c:/test.xml");
if ($data->{'row'}) {
   # Convert to hash, if it's array
   if (ref $data->{'row'} eq "HASH") {
       @$temp = ($data->{'row'});
       $data->{'row'} = $temp;    }
   if ($data->{'row'}->[0])    {
       my $count = 0;
       while($data->{'row'}->[$count]) {
         if (ref $data->{'row'}->[$count] eq "HASH") {
           print $data->{'row'}->[$count]->{'col1'}, ",";
           print $data->{'row'}->[$count]->{'col2'}, "\n"; }
         $count ++; }
   } }


使用XML::SimpleObject
xml


    
      /etc/dosemu.conf
      dosemu.conf-drdos703.eval
    
    
      /etc/passwd
      948
    
  


use XML::Parser;
use XML::SimpleObject;

my $file = 'c:/file.xml';

my $parser = XML::Parser->new(ErrorContext => 2, Style => "Tree");
my $xmlobj = XML::SimpleObject->new( $parser->parsefile($file) );

print "Files: \n";
foreach my $element ($xmlobj->child("files")->children("file"))
{
  print "  filename: " . $element->child("name")->value . "\n";
  if ($element->attribute("type"))
  {
    print "    type: " . $element->attribute("type") . "\n";
  }else{
  	print "    bytes: " . $element->child("bytes")->value . "\n";
  }
  
}  


生成xml
use XML::Writer;
  use IO::File;
  my $output = new IO::File(">output.xml");
  my $writer = new XML::Writer(OUTPUT => $output);
 #my $writer = XML::Writer->new();
  $writer->startTag("greeting", 
                    "class" => "simple");
  $writer->characters("Hello, world!");
  $writer->endTag("greeting");
  $writer->end();
  $output->close();

你可能感兴趣的:(XML,Perl,Java,C,C++)