Question

The manual page for XML::Parser::Style::Objects is horrible. A simple hello world style program would really be helpful.

I really wanted to do something like this: (not real code of course)

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";
}
Was it helpful?

Solution

In all cases here is actual code that runs ... doesn't mean much but produces output and hopefully can get you started ...

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();
}

with foo.xml

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

which outputs

>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

Hope that helps.

OTHER TIPS

When ever I need to do something similar, usually I end up using XML::Parser::EasyTree it has better documentation and is simpler to use.

I highly recommend it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top