2008-08-29 47 views
2

XML::Parser::Style::Objects的手冊頁很糟糕。一個簡單的hello世界風格的程序會真的有幫助。如何使用XML :: Parser和Style =>'Objects'

我真的很想做這樣的事情:(當然不是真正的代碼)

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"; 
} 

回答

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 

希望有幫助。

2

當過我需要做類似的東西,通常我最終使用XML::Parser::EasyTree它具有更好的文檔,簡單使用。

我強烈推薦它。

相關問題