fish3129 发表于 2018-8-31 09:16:57

perl XML::Parser使用object方法处理XML

  参考资料:http://search.cpan.org/~msergeant/XML-Parser-2.36/Parser.pm中的Object解说。
  操作文件:
  # cat sample1
  
  
  Partly Cloudy
  
  12
  6
  
  #
  脚本:
  # cat sample3.pl
  #!/usr/bin/perl -w
  use strict;
  use XML::Parser;
  my $file = "sample1";
  my $p = XML::Parser->new(Style =>'Objects');
  my $doc = $p->parsefile($file);
  process_node($doc->);
  sub process_node {
  my($node) = @_;
  my $type = ref $node;
  $type =~ s/^.*:://;
  if ($type eq 'OUTLOOK') {
  my $attr = {%$node};
  my $outlook = $attr->{Kids}->;
  my $outlookcont = $outlook->{Text};
  exchange($outlookcont);
  }elsif ($type eq 'TEMPERATURE') {
  my $attr = {%$node};
  my $temperature = $attr->{Kids}->;
  my $tempnum = $temperature->{Text};
  print "$attr->{TYPE}:",$tempnum," $attr->{DEGREES}","\n";
  }
  else {
  foreach my $node (@{$node->{Kids}}) {
  process_node($node);
  }
  }
  }
  sub exchange {
  my $value = shift;
  $value =~ s/\n/ /g;
  $value =~ s/^\s+//;
  $value =~ s/\s+$//;
  print "OUTLOOK: $value\n";
  }
  #
  执行结果:
  # perl sample3.pl
  OUTLOOK: Partly Cloudy
  MAX:12 C
  MIN:6 C
  #
  脚本解说:
  想要明白Object怎么操纵XML的,需要理解经过Object之后的XML生成的数据结构是怎么样的,比如:使用Data::Dumper来分析下生成的数据结构,然后去操作该数据结构即可。

页: [1]
查看完整版本: perl XML::Parser使用object方法处理XML