lib/XML/Hash/LX.pm

filter: Statementstmt 85.7% 12 / 14 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 89.4% 17 / 19 CC 1 SCAR 0.6
CC
1
Cov
86%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1 package XML::Hash::LX;
2  
3 5 ▶use 5.006002;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 5 ▶use XML::LibXML ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 0 ▶use Types::Serialiser;
Subroutine BEGIN: called CC=1 SCAR=2.6
8  
9 our $PARSER = XML::LibXML->new();
10  
11 sub _croak { require Carp; goto &Carp::croak }
12 sub import {
13 my $me = shift;
14 no strict 'refs';
15 my %e = ( xml2hash => 1, hash2xml => 1, ':inject' => 0 );
16 if (@_) { %e = map { $_=>1 } @_ }
17 *{caller().'::xml2hash'} = \&xml2hash if delete $e{xml2hash};
18 *{caller().'::hash2xml'} = \&hash2xml if delete $e{hash2xml};
19 if ( delete $e{':inject'} ) {
20 unless (defined &XML::LibXML::Node::toHash) {
21 *XML::LibXML::Node::toHash = \&xml2hash;
22 }
23 }
24 _croak "@{[keys %e]} is not exported by $me" if %e;
25 }
26  
27 =head1 NAME
28  
29 XML::Hash::LX - Convert hash to xml and xml to hash using LibXML
30  
31 =cut
32  
33 our $VERSION = '0.07';
34  
35 =head1 SYNOPSIS
36  
37 use XML::Hash::LX;
38  
39 my $hash = xml2hash $xmlstring, attr => '.', text => '~';
40 my $hash = xml2hash $xmldoc;
41
42 my $xmlstr = hash2html $hash, attr => '+', text => '#text';
43 my $xmldoc = hash2html $hash, doc => 1, attr => '+';
44
45 # Usage with XML::LibXML
46  
47 my $doc = XML::LibXML->new->parse_string($xml);
48 my $xp = XML::LibXML::XPathContext->new($doc);
49 $xp->registerNs('rss', 'http://purl.org/rss/1.0/');
50  
51 # then process xpath
52 for ($xp->findnodes('//rss:item')) {
53 # and convert to hash concrete nodes
54 my $item = xml2hash($_);
55 print Dumper+$item
56 }
57  
58 =head1 DESCRIPTION
59  
60 This module is a companion for C<XML::LibXML>. It operates with LibXML objects, could return or accept LibXML objects, and may be used for easy data transformations
61  
62 It is faster in parsing then L<XML::Simple>, L<XML::Hash>, L<XML::Twig> and of course much slower than L<XML::Bare> ;)
63  
64 It is faster in composing than L<XML::Hash>, but slower than L<XML::Simple>
65  
66 Parse benchmark:
67  
68 Rate Simple Hash Twig Hash::LX Bare
69 Simple 11.3/s -- -2% -16% -44% -97%
70 Hash 11.6/s 2% -- -14% -43% -97%
71 Twig 13.5/s 19% 16% -- -34% -96%
72 Hash::LX 20.3/s 79% 75% 51% -- -95%
73 Bare 370/s 3162% 3088% 2650% 1721% --
74  
75 Compose benchmark:
76  
77 Rate Hash Hash::LX Simple
78 Hash 49.2/s -- -18% -40%
79 Hash::LX 60.1/s 22% -- -26%
80 Simple 81.5/s 66% 36% --
81  
82 Benchmark was done on L<http://search.cpan.org/uploads.rdf>
83  
84 =head1 EXPORT
85  
86 C<xml2hash> and C<hash2xml> are exported by default
87  
88 =head2 :inject
89  
90 Inject toHash method in the namespace of L<XML::LibXML::Node> and allow to call it on any subclass of L<XML::LibXML::Node> directly
91  
92 By default is disabled
93  
94 use XML::Hash::LX ':inject';
95
96 my $doc = XML::LibXML->new->parse_string($xml);
97 my $hash = $doc->toHash(%opts);
98  
99 =head1 FUNCTIONS
100  
101 =head2 xml2hash $xml, [ OPTIONS ]
102  
103 XML could be L<XML::LibXML::Document>, L<XML::LibXML::DocumentPart> or string
104  
105 =head2 hash2xml $hash, [ doc => 1, ] [ OPTIONS ]
106  
107 Id C<doc> option is true, then returned value is L<XML::LibXML::Document>, not string
108  
109 =head1 OPTIONS
110  
111 Every option could be passed as arguments to function or set as global variable in C<XML::Hash::LX> namespace
112  
113 =head2 %XML::Hash::LX::X2H
114  
115 Options respecting convertations from xml to hash
116  
117 =over 4
118  
119 =item order [ = 0 ]
120  
121 B<Strictly> keep the output order. When enabled, structures become more complex, but xml could be completely reverted
122  
123 =item attr [ = '-' ]
124  
125 Attribute prefix
126  
127 <node attr="test" /> => { node => { -attr => "test" } }
128  
129 =item text [ = '#text' ]
130  
131 Key name for storing text
132  
133 <node>text<sub /></node> => { node => { sub => '', '#text' => "test" } }
134  
135 =item join [ = '' ]
136  
137 Join separator for text nodes, splitted by subnodes
138  
139 Ignored when C<order> in effect
140  
141 # default:
142 xml2hash( '<item>Test1<sub />Test2</item>' )
143 : { item => { sub => '', '~' => 'Test1Test2' } };
144
145 # global
146 $XML::Hash::LX::X2H{join} = '+';
147 xml2hash( '<item>Test1<sub />Test2</item>' )
148 : { item => { sub => '', '~' => 'Test1+Test2' } };
149
150 # argument
151 xml2hash( '<item>Test1<sub />Test2</item>', join => '+' )
152 : { item => { sub => '', '~' => 'Test1+Test2' } };
153  
154 =item trim [ = 1 ]
155  
156 Trim leading and trailing whitespace from text nodes
157  
158 =item cdata [ = undef ]
159  
160 When defined, CDATA sections will be stored under this key
161  
162 # cdata = undef
163 <node><![CDATA[ test ]]></node> => { node => 'test' }
164  
165 # cdata = '#'
166 <node><![CDATA[ test ]]></node> => { node => { '#' => 'test' } }
167  
168 =item comm [ = undef ]
169  
170 When defined, comments sections will be stored under this key
171  
172 When undef, comments will be ignored
173  
174 # comm = undef
175 <node><!-- comm --><sub/></node> => { node => { sub => '' } }
176  
177 # comm = '/'
178 <node><!-- comm --><sub/></node> => { node => { sub => '', '/' => 'comm' } }
179  
180 =item load_ext_dtd [ = 0 ]
181  
182 Load the external DTD
183  
184 # load_ext_dtd = 0
185 <!DOCTYPE foo [<!ENTITY % ent1 SYSTEM "rm -rf /">%ent1; ]><node> text</node>
186
187 # load_ext_dtd = 1
188 <!DOCTYPE foo [<!ENTITY % ent1 SYSTEM "rm -rf /">%ent1; ]><node> text</node>
189 oops!
190  
191  
192 =item expand_entities [ = 0 ]
193  
194 Enable XInclude substitution. (See L<XML::LibXML::Parser>)
195  
196 =item expand_xinclude [ = 0 ]
197  
198 Enable entities expansion. (See L<XML::LibXML::Parser>). (Enabling also enables load_ext_dtd)
199  
200 =item validation [ = 0 ]
201  
202 Enable validating with the DTD. (See L<XML::LibXML::Parser>)
203  
204 =item no_network [ = 1 ]
205  
206 Forbid network access; (See L<XML::LibXML::Parser>)
207  
208 If true, all attempts to fetch non-local resources (such as DTD or external entities) will fail
209  
210 =back
211  
212 =head2 $XML::Hash::LX::X2A [ = 0 ]
213  
214 Global array casing
215  
216 Ignored when C<X2H{order}> in effect
217  
218 As option should be passed as
219  
220 xml2hash $xml, array => 1;
221  
222 Effect:
223  
224 # $X2A = 0
225 <node><sub/></node> => { node => { sub => '' } }
226  
227 # $X2A = 1
228 <node><sub/></node> => { node => [ { sub => [ '' ] } ] }
229  
230 =head2 %XML::Hash::LX::X2A
231  
232 By element array casing
233  
234 Ignored when C<X2H{order}> in effect
235  
236 As option should be passed as
237  
238 xml2hash $xml, array => [ nodes list ];
239  
240 Effect:
241  
242 # %X2A = ()
243 <node><sub/></node> => { node => { sub => '' } }
244  
245 # %X2A = ( sub => 1 )
246 <node><sub/></node> => { node => { sub => [ '' ] } }
247  
248 =cut
249  
250 our $X2A = 0;
251 our %X2A = ();
252  
253 our %X2H;
254 %X2H = (
255 order => 0,
256 attr => '-',
257 text => '#text',
258 join => '',
259 trim => 1,
260 cdata => undef,
261 comm => undef,
262 #cdata => '#',
263 #comm => '//',
264 load_ext_dtd => 0,
265 expand_entities => 0,
266 expand_xinclude => 0,
267 validation => 0,
268 no_network => 1,
269 %X2H, # also inject previously user-defined options
270 );
271  
272 sub _x2h {
273 my $doc = shift;
274 my $res;
275 if ($doc->hasChildNodes or $doc->hasAttributes) {
276 if ($X2H{order}) {
277 $res = [];
278 my $attr = {};
279 for ($doc->attributes) {
280 #warn " .> ".$_->nodeName.'='.$_->getValue;
281 $attr->{ $X2H{attr} . $_->nodeName } = $_->getValue;
282 }
283 push @$res, $attr if %$attr;
284 } else {
285 $res = {};
286 for ($doc->attributes) {
287 #warn " .> ".$_->nodeName.'='.$_->getValue;
288 $res->{ $X2H{attr} . $_->nodeName } = $_->getValue;
289 }
290 }
291 for ($doc->childNodes) {
292 my $ref = ref $_;
293 my $nn;
294 if ($ref eq 'XML::LibXML::Text') {
295 $nn = $X2H{text}
296 }
297 elsif ($ref eq 'XML::LibXML::CDATASection') {
298 $nn = defined $X2H{cdata} ? $X2H{cdata} : $X2H{text};
299 }
300 elsif ($ref eq 'XML::LibXML::Comment') {
301 $nn = defined $X2H{comm} ? $X2H{comm} : next;
302 }
303 else {
304 $nn = $_->nodeName;
305 }
306 my $chld = _x2h($_);
307 if ($X2H{order}) {
308 if ($nn eq $X2H{text}) {
309 push @{ $res }, $chld if length $chld;
310 } else {
311 push @{ $res }, { $nn => $chld };
312 }
313 } else {
314 if (( $X2A or $X2A{$nn} ) and !$res->{$nn}) { $res->{$nn} = [] }
315 if (exists $res->{$nn} ) {
316 #warn "Append to $res->{$nn}: $nn $chld";
317 $res->{$nn} = [ $res->{$nn} ] unless ref $res->{$nn} eq 'ARRAY';
318 push @{$res->{$nn}}, $chld if defined $chld;
319 } else {
320 if ($nn eq $X2H{text}) {
321 $res->{$nn} = $chld if length $chld;
322 } else {
323 $res->{$nn} = $chld;
324 }
325 }
326 }
327 }
328 if($X2H{order}) {
329 #warn "Ordered mode, have res with ".(0+@$res)." children = @$res";
330 return $res->[0] if @$res == 1;
331 } else {
332 if (defined $X2H{join} and exists $res->{ $X2H{text} } and ref $res->{ $X2H{text} }) {
333 $res->{ $X2H{text} } = join $X2H{join}, grep length, @{ $res->{ $X2H{text} } };
334 }
335 delete $res->{ $X2H{text} } if $X2H{trim} and keys %$res > 1 and exists $res->{ $X2H{text} } and !length $res->{ $X2H{text} };
336 return $res->{ $X2H{text} } if keys %$res == 1 and exists $res->{ $X2H{text} };
337 }
338 }
339 else {
340 $res = $doc->textContent;
341 if ($X2H{trim}) {
342 $res =~ s{^\s+}{}s;
343 $res =~ s{\s+$}{}s;
344 }
345 }
346 $res;
347
348 }
349  
350 sub xml2hash($;%) {
351 my $doc = shift;
352 defined $doc or _croak("Called xml2hash on undef"),return;
353 my %opts = @_;
354 my $arr = delete $opts{array};
355 local $X2A = 1 if defined $arr and !ref $arr;
356 local @X2A{@$arr} = (1)x@$arr if defined $arr and ref $arr;
357 local @X2H{keys %opts} = values %opts if @_;
358 $PARSER->load_ext_dtd($X2H{load_ext_dtd});
359 $PARSER->expand_entities($X2H{expand_entities});
360 $PARSER->expand_xinclude($X2H{expand_xinclude});
361 $PARSER->validation($X2H{validation});
362 $PARSER->no_network($X2H{no_network});
363  
364 $doc = $PARSER->parse_string($doc) if !ref $doc;
365 #use Data::Dumper;
366 #warn Dumper \%X2H;
367 my $root = $doc->isa('XML::LibXML::Document') ? $doc->documentElement : $doc;
368 return {
369 scalar $root->nodeName => $X2A || $X2A{$root->nodeName} ? [ _x2h($root) ] : _x2h($root),
370 };
371  
372 }
373  
374 =head2 %XML::Hash::LX::H2X
375  
376 Options respecting convertations from hash to xml
377  
378 =over 4
379  
380 =item encoding [ = 'utf-8' ]
381  
382 XML output encoding
383  
384 =item attr [ = '-' ]
385  
386 Attribute prefix
387  
388 { node => { -attr => "test", sub => 'test' } }
389 <node attr="test"><sub>test</sub></node>
390  
391 =item text [ = '#text' ]
392  
393 Key name for storing text
394  
395 { node => { sub => '', '#text' => "test" } }
396 <node>text<sub /></node>
397 # or
398 <node><sub />text</node>
399 # order of keys is not predictable
400  
401 =item trim [ = 1 ]
402  
403 Trim leading and trailing whitespace from text nodes
404  
405 # trim = 1
406 { node => { sub => [ ' ', 'test' ], '#text' => "test" } }
407 <node>test<sub>test</sub></node>
408  
409 # trim = 0
410 { node => { sub => [ ' ', 'test' ], '#text' => "test" } }
411 <node>test<sub> test</sub></node>
412  
413 =item cdata [ = undef ]
414  
415 When defined, such key elements will be saved as CDATA sections
416  
417 # cdata = undef
418 { node => { '#' => 'test' } } => <node><#>test</#></node> # it's bad ;)
419  
420 # cdata = '#'
421 { node => { '#' => 'test' } } => <node><![CDATA[test]]></node>
422  
423 =item comm [ = undef ]
424  
425 When defined, such key elements will be saved as comment sections
426  
427 # comm = undef
428 { node => { '/' => 'test' } } => <node></>test<//></node> # it's very bad! ;)
429  
430 # comm = '/'
431 { node => { '/' => 'test' } } => <node><!-- test --></node>
432  
433 =back
434  
435 =cut
436  
437 our %H2X;
438 %H2X = (
439 %X2H,
440 #attr => '-',
441 #text => '~',
442 #trim => 1,
443 # join => '+', # useless
444 %H2X,
445 );
446 our $AL = length $H2X{attr};
447  
448 our $hd = '/';
449 sub _h2x {
450 @_ or return;
451 my ($data,$parent) = @_;
452 #warn "> $d";
453 return unless defined $data;
454 if ( !ref $data ) {
455 if ($H2X{trim}) {
456 $data =~ s/^\s+//s;
457 $data =~ s/\s+$//s;
458 #return unless length($data);
459 }
460 return XML::LibXML::Text->new($data)
461 };
462 my @rv;
463 if (ref $data eq 'ARRAY') {
464 #warn "Map @$data";
465 @rv = map _h2x($_,$parent), @$data;
466 }
467 elsif (ref $data eq 'HASH') {
468 for (keys %$data) {
469 #warn "$_ $data->{$_}";
470 #next if !defined $data->{$_} or ( !ref $data->{$_} and !length $data->{$_} );
471
472 # What may be empty ?
473 # - attribute
474 # - node
475 # - comment
476 # Skip empty: text, cdata
477
478 my $cdata_or_text;
479
480 if ($_ eq $H2X{text}) {
481 $cdata_or_text = 'XML::LibXML::Text';
482 }
483 elsif (defined $H2X{cdata} and $_ eq $H2X{cdata}) {
484 $cdata_or_text = 'XML::LibXML::CDATASection';
485 }
486
487 if (0) {}
488
489 elsif($cdata_or_text) {
490 push @rv, map {
491 defined($_) ? do {
492 $H2X{trim} and s/(?:^\s+|\s+$)//sg;
493 $H2X{trim} && !length($_) ? () :
494 $cdata_or_text->new( $_ )
495 } : (),
496 } ref $data->{$_} ? @{ $data->{$_} } : $data->{$_};
497
498 }
499 elsif (defined $H2X{comm} and $_ eq $H2X{comm}) {
500 push @rv, map XML::LibXML::Comment->new(defined $_ ? $_ : ''), ref $data->{$_} ? @{ $data->{$_} } : $data->{$_};
501 }
502 elsif (substr($_,0,$AL) eq $H2X{attr} ) {
503 if ($parent) {
504 $parent->setAttribute( substr($_,1),defined $data->{$_} ? $data->{$_} : '' );
505 } else {
506 warn "attribute $_ without parent"
507 }
508 }
509 elsif ( !defined $data->{$_} or ( !ref $data->{$_} and !length $data->{$_} ) ) {
510 push @rv,XML::LibXML::Element->new($_);
511 }
512 else {
513 local $hd = $hd.'/'.$_;
514 my $node = XML::LibXML::Element->new($_);
515 #warn ("$hd << ".$_->nodeName),
516 $node->appendChild($_) for _h2x($data->{$_},$node);
517 push @rv,$node;
518 }
519 }
520 }
521 elsif (ref $data eq 'SCALAR') { # RAW
522 my $node = eval { XML::LibXML->new->parse_string($$data) } or _croak "Malformed raw data on $hd: $@";
523 return $node->documentElement;
524 }
525 elsif (ref $data eq 'REF') { # LibXML Node
526 if (ref $$data and eval{ $$data->isa('XML::LibXML::Node') }) {
527 return $$data->cloneNode(1);
528 }
529 elsif ( ref $$data and do { no strict 'refs'; exists ${ ref($$data).'::' }{'(""'} } ) {
530 return XML::LibXML::Text->new( "$$data" );
531 }
532 else {
533 _croak ("Bad reference ".ref( $$data ).": <$$data> on $hd");
534 }
535 }
536 elsif (Types::Serialiser::is_bool( $data )) {
537 return XML::LibXML::Text->new( $data ? "true" : "false" );
538 }
539 elsif ( do { no strict 'refs'; exists ${ ref($data).'::' }{'(""'} } ) { # have string overload
540 return XML::LibXML::Text->new( "$data" );
541 }
542 elsif (ref $data and eval{ $data->isa('XML::LibXML::Node') }) {
543 return $data->cloneNode(1);
544 }
545 else {
546 _croak "Bad reference ".ref( $data ).": <$data> on $hd";
547 }
548 #warn "@rv";
549 return wantarray ? @rv : $rv[0];
550 }
551  
552 sub hash2xml($;%) {
553 #warn "hash2xml(@_) from @{[ (caller)[1,2] ]}";
554 my $hash = shift;
555 my %opts = @_;
556 my $str = delete $opts{doc} ? 0 : 1;
557 my $encoding = delete $opts{encoding} || delete $opts{enc} || 'utf-8';
558 my $doc = XML::LibXML::Document->new('1.0', $encoding);
559 local @H2X{keys %opts} = values %opts if @_;
560 local $AL = length $H2X{attr};
561 #use Data::Dumper;
562 #warn Dumper \%H2X;
563 my $root = _h2x($hash);
564 $doc->setDocumentElement($root);
565 return $str ? $doc->toString : $doc;
566 }
567  
568  
569 =head1 BUGS
570  
571 None known
572  
573 =head1 SEE ALSO
574  
575 =over 4
576  
577 =item * L<XML::Parser::Style::EasyTree>
578  
579 With default settings should produce the same output as this module. Settings are similar by effect
580  
581 =back
582  
583 =head1 AUTHOR
584  
585 Mons Anderson, C<< <mons at cpan.org> >>
586  
587 =head1 LICENSE
588  
589 Copyright 2009-2020 Mons Anderson, all rights reserved.
590  
591 This program is free software; you can redistribute it and/or modify it
592 under the same terms as Perl itself.
593  
594 =cut
595  
596 1; # End of XML::Hash::LX
↑ Summary