Pregunta

La página del manual para XML::Parser::Style::Objects es horrible.Un programa sencillo de estilo Hola Mundo sería realmente útil.

Realmente quería hacer algo como esto:(no es un código real, por supuesto)

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";
}
¿Fue útil?

Solución

En todos los casos, aquí hay código real que se ejecuta...no significa mucho, pero produce resultados y, con suerte, puede ayudarlo a comenzar ...

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

con foo.xml

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

que salidas

>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

Espero que ayude.

Otros consejos

Cuando necesito hacer algo similar, normalmente termino usando XML::Analizador::EasyTree tiene mejor documentación y es más sencillo de usar.

Lo recomiendo altamente.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top