Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use XML::Parser with Style => 'Objects'

Tags:

xml

perl

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";
}
like image 607
Jeremy Avatar asked Dec 15 '25 21:12

Jeremy


1 Answers

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.

like image 138
Pat Avatar answered Dec 18 '25 01:12

Pat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!