如何在Style =>中使用XML :: Parser? “对象”

时间:2008-08-29 18:12:01

标签: xml perl

XML::Parser::Style::Objects的手册页非常糟糕。一个简单的hello世界风格的程序真的很有帮助。

我真的想做这样的事情:(当然不是真正的代码)

use XML::Parser;
my $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode');
my $tree = $p->parsefile('foo.xml');
$tree->doSomething();

MyNode::doSomething() {
  my $self = shift;
  print "This is a normal node";
  for $kid ($self->Kids)
  {
    $kid->doSomething();
  }
}

MyNode::special::doSomething() {
  my $self = shift;
  print "This is a special node";
}

2 个答案:

答案 0 :(得分:2)

当我需要做类似的事情时,通常我最终会使用XML::Parser::EasyTree 它有更好的文档并且使用起来更简单。

我强烈推荐它。

答案 1 :(得分:1)

在所有情况下,这里都是运行的实际代码......并不意味着产生输出,希望能让你开始......

use XML::Parser;

package MyNode::inner;
    sub doSomething {
      my $self = shift;
      print "This is an inner node containing : ";
      print $self->{Kids}->[0]->{Text};
      print "\n";
    }
package MyNode::Characters;
    sub doSomething {}
package MyNode::foo;
    sub doSomething {
      my $self = shift;
      print "This is an external node\n";
      for $kid (@ { $self->{Kids} }) {
        $kid->doSomething();
      }
    }

package main;

my $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode');
my $tree = $p->parsefile('foo.xml');
for (@$tree) {
    $_->doSomething();
}

使用foo.xml

 <foo> <inner>some text</inner> <inner>something else</inner></foo>

输出

>perl -w "tree.pl"     
This is an external node
This is an inner node containing : some text
This is an inner node containing : something else

希望有所帮助。