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