File Coverage

blib/lib/XML/Crawler.pm
Criterion Covered Total %
statement 10 12 83.3
branch n/a
condition n/a
subroutine 4 4 100.0
pod n/a
total 14 16 87.5


line stmt bran cond sub pod time code
1             package XML::Crawler;
2              
3 1     1   26356 use strict;
  1         3  
  1         40  
4 1     1   5 use warnings;
  1         2  
  1         33  
5              
6 1     1   863 use English qw( -no_match_vars $EVAL_ERROR );
  1         4990  
  1         6  
7 1     1   700 use XML::LibXML;
  0            
  0            
8             require Exporter;
9              
10             our @ISA = qw( Exporter );
11              
12             our @EXPORT_OK = qw(
13             xml_to_ra
14             );
15              
16             our $VERSION = '0.01';
17              
18             sub xml_to_ra {
19             my ($xml) = @_;
20              
21             my $doc;
22              
23             eval {
24             $doc = XML::LibXML->load_xml( string => $xml );
25             };
26              
27             return
28             if $EVAL_ERROR;
29              
30             return {}
31             if not $doc;
32              
33             return _crawl($doc);
34             }
35              
36             sub _crawl {
37             my ( $node ) = @_;
38              
39             my $name = $node->nodeName();
40             my %attributes = map { ( $_->nodeName() => $_->getValue() ) } grep { $_ } $node->attributes();
41             my $text;
42             my @children;
43              
44             my @child_nodes = $node->nonBlankChildNodes();
45              
46             if (@child_nodes) {
47              
48             @children = map { _crawl( $_ ) } @child_nodes;
49              
50             if ( @children == 1 && not ref $children[0] ) {
51              
52             $text = pop @children;
53             }
54             }
55             else {
56              
57             $text = $node->textContent();
58             }
59              
60             return $text
61             if $text && $name eq '#text';
62              
63             my @result = ( $name );
64              
65             push @result, \%attributes
66             if keys %attributes;
67              
68             push @result, $text
69             if $text;
70              
71             push @result, \@children
72             if @children;
73              
74             return \@result;
75             }
76              
77             1;
78              
79             __END__