| 1 |
use strict; |
| 2 |
use warnings; |
| 3 |
|
| 4 |
use XML::LibXML; |
| 5 |
use IO::File; |
| 6 |
|
| 7 |
# first instanciate the parser |
| 8 |
my $parser = XML::LibXML->new(); |
| 9 |
|
| 10 |
# initialize the callbacks |
| 11 |
$parser->match_callback( \&match_uri ); |
| 12 |
$parser->read_callback( \&read_uri ); |
| 13 |
$parser->open_callback( \&open_uri ); |
| 14 |
$parser->close_callback( \&close_uri ); |
| 15 |
|
| 16 |
# include XIncludes on the fly |
| 17 |
$parser->expand_xinclude( 1 ); |
| 18 |
|
| 19 |
# parse the file "text.xml" in the current directory |
| 20 |
my $dom = $parser->parse_file("test.xml"); |
| 21 |
|
| 22 |
print $dom->toString() , "\n"; |
| 23 |
|
| 24 |
# the callbacks follow |
| 25 |
# these callbacks are used for both the original parse AND the XInclude |
| 26 |
sub match_uri { |
| 27 |
my $uri = shift; |
| 28 |
return $uri !~ /:\/\// ? 1 : 0; # we handle only files |
| 29 |
} |
| 30 |
|
| 31 |
sub open_uri { |
| 32 |
my $uri = shift; |
| 33 |
|
| 34 |
my $handler = new IO::File; |
| 35 |
if ( not $handler->open( "<$uri" ) ){ |
| 36 |
$handler = 0; |
| 37 |
} |
| 38 |
|
| 39 |
return $handler; |
| 40 |
} |
| 41 |
|
| 42 |
sub read_uri { |
| 43 |
my $handler = shift; |
| 44 |
my $length = shift; |
| 45 |
my $buffer = undef; |
| 46 |
if ( $handler ) { |
| 47 |
$handler->read( $buffer, $length ); |
| 48 |
} |
| 49 |
return $buffer; |
| 50 |
} |
| 51 |
|
| 52 |
sub close_uri { |
| 53 |
my $handler = shift; |
| 54 |
if ( $handler ) { |
| 55 |
$handler->close(); |
| 56 |
} |
| 57 |
return 1; |
| 58 |
} |
| 59 |
|