perl中给hash转换成xml输出

八 13th, 2009

转载本站文章请注明,转载自:扶凯[http://www.php-oa.com]

本文链接: http://www.php-oa.com/2009/08/13/outputting-a-hash-as-xml.html

因为使用需要,做一个xml的接口.需要给hash转成xml,google了一下,发现了如下极品…得好好学习

#!/usr/bin/perl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use strict;
use XML::Twig;
 
my %all = (
 Video => {
        Width => '960pixels',
        CodecID => 'H264',
        Height => '540pixels',
  },
  Audio => {
        FormatInfo => 'AudioCoding3',
        Streamsize => '120MiB',
        Samplingrate => '48.0KHz',
  },
  General => {
        Format  => 'AVI',
        Duration => '43mn45s',
        Filesize => '436MiB',
  },
 );
 
my $twig = XML::Twig->new(pretty_print => 'indented');
my $elt = create_element(info => \%all);
$twig->set_root($elt);
$twig->print();
 
sub create_element{
    my $gi   = shift;
    my $data = shift;
    my $t = XML::Twig::Elt->new($gi);
 
    if (ref $data){
        while (my ($k,$v) = each(%$data)){
            create_element($k, $v)->paste(last_child => $t);
        }
    }else{
        $t->set_text($data);
    }
    $t;
}

测试,上面有个all的hash的hash.转换后如下输出

# perl test2.pl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<info>
  <Video>
    <Height>540pixels</Height>
    <Width>960pixels</Width>
    <CodecID>H264</CodecID>
  </Video>
  <General>
    <Filesize>436MiB</Filesize>
    <Duration>43mn45s</Duration>
    <Format>AVI</Format>
  </General>
  <Audio>
    <Samplingrate>48.0KHz</Samplingrate>
    <FormatInfo>AudioCoding3</FormatInfo>
    <Streamsize>120MiB</Streamsize>
  </Audio>
</info>
 
要是想输出到一个文件之类,可以用下面的方法

 

  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use XML::Writer;
  5.  
  6. print "Content-type: text/xml\n\n";
  7.  
  8. my $xml = new XML::Writer();
  9.  
  10. $xml->startTag("root");
  11.   $xml->startTag("messages");
  12.     $xml->dataElement(msg1=> "Hello World");   
  13.     $xml->dataElement(msg2=> "Goodbye World");
  14.     $xml->endTag();
  15.     $xml->endTag();
  16.   $xml->endTag();
  17. $xml->end();

参考:
www.perlmonks.org/
tech.idv2.com/2007/09/14/generate-xml-with-xml-dom/

                                                                                                              
 

Del.icio.us Google书签 Digg Live Bookmark Technorati Furl Yahoo书签 Facebook 百度搜藏 新浪 ViVi 365Key 网摘 天极网摘 和讯网摘 博拉网 POCO 网摘 饭否 QQ 书签 Digbuzz 我挖网 Mister Wong
标签:
目前还没有任何评论.