Debian Codegraph @

lib/XML/Hash/XS.pm

raw
1 package XML::Hash::XS;
2
3 use 5.008008;
4 use strict;
5 use warnings;
6 use vars qw($VERSION @EXPORT @EXPORT_OK);
7 use base 'Exporter';
8 @EXPORT = qw( hash2xml xml2hash );
9 @EXPORT_OK = (@EXPORT, qw(
10 XML_HASH_XS_CONTINUE XML_HASH_XS_STOP XML_HASH_XS_SKIP
11 ));
12
13 sub XML_HASH_XS_CONTINUE () { 'XML_HASH_XS_CONTINUE' }
14 sub XML_HASH_XS_STOP () { 'XML_HASH_XS_STOP' }
15 sub XML_HASH_XS_SKIP () { 'XML_HASH_XS_SKIP' }
16
17 $VERSION = '0.66';
18
19 require XSLoader;
20 XSLoader::load('XML::Hash::XS', $VERSION);
21
22 use vars qw($method $output $output_cb $root $version $encoding $utf8 $indent $canonical
23 $use_attr $content $xml_decl $doc $max_depth $attr $text $trim $cdata
24 $comm $buf_size $keep_root $force_array $force_content $merge_text
25 $suppress_empty $cb_mode
26 );
27
28 # 'NATIVE' or 'LX'
29 $method = 'NATIVE';
30
31 # native options
32 $output = undef;
33 $output_cb = undef;
34 $root = 'root';
35 $version = '1.0';
36 $encoding = '';
37 $utf8 = 1;
38 $indent = 0;
39 $canonical = 0;
40 $use_attr = 0;
41 $content = undef;
42 $xml_decl = 1;
43 $keep_root = 1;
44 $doc = 0;
45 $max_depth = 1024;
46 $buf_size = 4096;
47 $trim = 0;
48 $force_array = undef;
49 $force_content = 0;
50 $merge_text = 0;
51 $suppress_empty = 0;
52 $cb_mode = 'node';
53
54 # XML::Hash::LX options
55 $attr = '-';
56 $text = '#text';
57 $cdata = undef;
58 $comm = undef;
59
60 1;
61 __END__
62 =head1 NAME
63
64 XML::Hash::XS - Simple and fast hash to XML and XML to hash conversion written in C
65
66 =begin HTML
67
68 <p><a href="https://metacpan.org/pod/XML::Hash::XS" target="_blank"><img alt="CPAN version" src="https://badge.fury.io/pl/XML-Hash-XS.svg"></a> <a href="https://github.com/yoreek/XML-Hash-XS/actions/workflows/ci.yml" target="_blank"><img title="CI status" alt="CI status" src="https://github.com/yoreek/XML-Hash-XS/actions/workflows/ci.yml/badge.svg?branch=master"></a></p>
69
70 =end HTML
71
72 =head1 SYNOPSIS
73
74 use XML::Hash::XS;
75
76 my $xmlstr = hash2xml \%hash;
77 hash2xml \%hash, output => $fh;
78 hash2xml \%hash, output_cb => sub { my ($chunk) = @_; print $chunk };
79
80 my $hash = xml2hash $xmlstr;
81 my $hash = xml2hash \$xmlstr;
82 my $hash = xml2hash 'test.xml', encoding => 'cp1251';
83 my $hash = xml2hash $fh;
84 my $hash = xml2hash *STDIN;
85
86 Or OOP way:
87
88 use XML::Hash::XS qw();
89
90 my $conv = XML::Hash::XS->new(utf8 => 0, encoding => 'utf-8')
91 my $xmlstr = $conv->hash2xml(\%hash, utf8 => 1);
92 my $hash = $conv->xml2hash($xmlstr, encoding => 'cp1251');
93
94 For incremental XML input, create a parser:
95
96 my $parser = XML::Hash::XS::Parser->new(keep_root => 1);
97 $parser->feed('<root><item>one</item>');
98 $parser->feed('<item>two</item></root>');
99 my $hash = $parser->finish;
100
101 Chunks must be UTF-8; bytes are retained only when a token spans two calls
102 to C<feed>.
103
104 =head1 DESCRIPTION
105
106 This module implements simple hash to XML and XML to hash conversion written in C.
107
108 During conversion uses minimum of memory, XML or hash is written directly without building DOM.
109
110 Some features are optional and are available with appropriate libraries:
111
112 =over 2
113
114 =item * XML::LibXML library is required in order to build DOM
115
116 =item * ICU or iconv library is required in order to perform charset conversions
117
118 =back
119
120 =head1 FUNCTIONS
121
122 =head2 hash2xml $hash, [ %options ]
123
124 $hash is reference to hash
125
126 hash2xml
127 {
128 node1 => 'value1',
129 node2 => [ 'value21', { node22 => 'value22' } ],
130 node3 => \'value3',
131 node4 => sub { return 'value4' },
132 node5 => sub { return { node51 => 'value51' } },
133 },
134 canonical => 1,
135 indent => 2,
136 ;
137
138 will convert to:
139
140 <?xml version="1.0" encoding="utf-8"?>
141 <root>
142 <node1>value1</node1>
143 <node2>value21</node2>
144 <node2>
145 <node22>value22</node22>
146 </node2>
147 <node3>value3</node3>
148 <node4>value4</node4>
149 <node5>
150 <node51>value51</node51>
151 </node5>
152 </root>
153
154 and (use_attr=1):
155
156 hash2xml
157 {
158 node1 => 'value1',
159 node2 => [ 'value21', { node22 => 'value22' } ],
160 node3 => \'value3',
161 node4 => sub { return 'value4' },
162 node5 => sub { return { node51 => 'value51' } },
163 },
164 use_attr => 1,
165 canonical => 1,
166 indent => 2,
167 ;
168
169 will convert to:
170
171 <?xml version="1.0" encoding="utf-8"?>
172 <root node1="value1" node3="value3" node4="value4">
173 <node2>value21</node2>
174 <node2 node22="value22"/>
175 <node5 node51="value51"/>
176 </root>
177
178
179 =head2 xml2hash $xml, [ %options ]
180
181 $xml may be string, reference to string, file handle or tied file handle:
182
183 xml2hash '<root>text</root>';
184 # output: 'text'
185
186 xml2hash '<root a="1" b="2">text</root>';
187 # output: { a => '1', b => '2', content => 'text' }
188
189 open(my $fh, '<', 'test.xml');
190 xml2hash $fh;
191
192 xml2hash *STDIN;
193
194 =head1 OPTIONS
195
196 =over 4
197
198 =item doc [ => 0 ] I<# hash2xml>
199
200 if doc is '1', then returned value is L<XML::LibXML::Document>.
201
202 =item root [ = 'root' ] I<# hash2xml>
203
204 Root node name.
205
206 =item version [ = '1.0' ] I<# hash2xml>
207
208 XML document version
209
210 =item encoding [ = 'utf-8' ] I<# hash2xml+xml2hash>
211
212 XML input/output encoding
213
214 =item indent [ = 0 ] I<# hash2xml>
215
216 if indent great than "0", XML output should be indented according to its hierarchic structure.
217 This value determines the number of spaces.
218
219 if indent is "0", XML output will all be on one line.
220
221 =item output [ = undef ] I<# hash2xml>
222
223 XML output method
224
225 if output is undefined, XML document dumped into string.
226
227 if output is FH, XML document writes directly to a filehandle or a stream.
228
229 =item output_cb [ = undef ] I<# hash2xml>
230
231 Callback invoked as C<< sub { my ($chunk) = @_ } >> for each generated XML
232 chunk. The complete XML string is not accumulated and C<hash2xml> returns
233 undef. Chunk size is controlled by C<buf_size>, except that a single value may
234 require a larger chunk. C<output> and C<output_cb> are mutually exclusive.
235
236 =item canonical [ = 0 ] I<# hash2xml>
237
238 if canonical is "1", converter will be write hashes sorted by key.
239
240 if canonical is "0", order of the element will be pseudo-randomly.
241
242 =item use_attr [ = 0 ] I<# hash2xml>
243
244 if use_attr is "1", converter will be use the attributes.
245
246 if use_attr is "0", converter will be use tags only.
247
248 =item content [ = undef ] I<# hash2xml+xml2hash>
249
250 if defined that the key name for the text content(used only if use_attr=1).
251
252 =item force_array => [ = undef ] I<# xml2hash>
253
254 This option is similar to "ForceArray" from XML::Simple module: L<https://metacpan.org/pod/XML::Simple#ForceArray-=%3E-1-%23-in-important>.
255
256 =item force_content => [ = 0 ] I<# xml2hash>
257
258 This option is similar to "ForceContent" from XML::Simple module: L<https://metacpan.org/pod/XML::Simple#ForceContent-=%3E-1-%23-in-seldom-used>.
259
260 =item merge_text [ = 0 ] I<# xml2hash>
261
262 Setting this option to "1" will cause merge adjacent text nodes.
263
264 =item xml_decl [ = 1 ] I<# hash2xml>
265
266 if xml_decl is "1", output will start with the XML declaration '<?xml version="1.0" encoding="utf-8"?>'.
267
268 if xml_decl is "0", XML declaration will not be output.
269
270 =item trim [ = 0 ] I<# hash2xml+xml2hash>
271
272 Trim leading and trailing whitespace from text nodes.
273
274 =item suppress_empty => [ = 0 ] I<# xml2hash>
275
276 This option is similar to "SuppressEmpty" from XMl::Simple module: L<https://metacpan.org/pod/XML::Simple#SuppressEmpty-=%3E-1-%7C-''-%7C-undef-%23-in+out-handy>.
277
278 =item utf8 [ = 1 ] I<# hash2xml+xml2hash>
279
280 Turn on utf8 flag for strings if enabled.
281
282 =item max_depth [ = 1024 ] I<# xml2hash>
283
284 Maximum recursion depth.
285
286 =item buf_size [ = 4096 ] I<# hash2xml+xml2hash>
287
288 Buffer size for reading end encoding data.
289
290 =item keep_root [ = 1 ] I<# hash2xml+xml2hash>
291
292 Keep root element.
293
294 =item filter [ = undef ] I<# xml2hash>
295
296 Filter nodes matched by pattern and return reference to array of nodes.
297
298 Sample:
299
300 my $xml = <<'XML';
301 <root>
302 <item1>111</item1>
303 <item2>222</item2>
304 <item3>333</item3>
305 </root>
306 XML
307
308 my $nodes = xml2hash($xml, filter => '/root/item1');
309 # $nodes = [ 111 ]
310
311 my $nodes = xml2hash($xml, filter => ['/root/item1', '/root/item2']);
312 # $nodes = [ 111, 222 ]
313
314 my $nodes = xml2hash($xml, filter => qr[/root/item\d$]);
315 # $nodes = [ 111, 222, 333 ]
316
317 It may be used to parse large XML because does not require a lot of memory.
318
319 =item cb [ = undef ] I<# xml2hash>
320
321 This option is used in conjunction with "filter" option and defines callback
322 that will called for each matched node.
323
324 Sample:
325
326 xml2hash($xml, filter => qr[/root/item\d$], cb => sub {
327 print $_[0], "\n";
328 });
329 # 111
330 # 222
331 # 333
332
333 The callback may return C<XML_HASH_XS_STOP> to stop successfully after the
334 current matched node. Other return values preserve the legacy behaviour and
335 continue parsing.
336
337 =item cb_mode [ = 'node' ] I<# xml2hash>
338
339 With C<cb_mode =E<gt> 'events'> the callback receives
340 C<($event, $value, $meta)>. A C<start> event contains element C<name>, C<path>,
341 C<depth> and C<attributes> in C<$meta>. Returning C<XML_HASH_XS_SKIP> from
342 C<start> skips construction of the element contents and suppresses its
343 C<end> event. C<end> receives the completed node in C<$value>.
344
345 The control constants are imported explicitly:
346
347 use XML::Hash::XS qw(
348 XML_HASH_XS_CONTINUE XML_HASH_XS_STOP XML_HASH_XS_SKIP
349 );
350
351 =item method [ = 'NATIVE' ] I<# hash2xml>
352
353 experimental support the conversion methods other libraries
354
355 if method is 'LX' then conversion result is the same as using L<XML::Hash::LX> library
356
357 Note: for 'LX' method following additional options are available:
358 attr
359 cdata
360 text
361 comm
362
363 =back
364
365 =head1 OBJECT SERIALISATION(hash2xml)
366
367 =over 2
368
369 =item 1. When object has a "toString" method
370
371 In this case, the <toString> method of object is invoked in scalar context.
372 It must return a single scalar that can be directly encoded into XML.
373
374 Example:
375
376 use XML::LibXML;
377 local $XML::LibXML::skipXMLDeclaration = 1;
378 my $doc = XML::LibXML->new->parse_string('<foo bar="1"/>');
379 print hash2xml({ doc => $doc }, indent => 2, xml_decl => 0);
380 =>
381 <root>
382 <doc><foo bar="1"/></doc>
383 </root>
384
385 =item 2. When object has overloaded stringification
386
387 In this case, the stringification method of object is invoked and result is directly encoded into XML.
388
389 Example:
390
391 package Test {
392 use overload '""' => sub { shift->stringify }, fallback => 1;
393 sub new {
394 my ($class, $str) = @_;
395 bless { str => $str }, $class;
396 }
397 sub stringify {
398 shift->{str}
399 }
400 }
401 my $obj = Test->new('test string');
402 print hash2xml({ obj => $obj }, indent => 2, xml_decl => 0);
403 =>
404 <root>
405 <obj>test string</obj>
406 </root>
407
408 =item 3. When object has a "iternext" method ("NATIVE" method only)
409
410 In this case, the <iternext> method method will invoke a few times until the return value is not undefined.
411
412 Example:
413
414 my $count = 0;
415 my $o = bless {}, 'Iterator';
416 *Iterator::iternext = sub { $count++ < 3 ? { count => $count } : undef };
417 print hash2xml({ item => $o }, use_attr => 1, indent => 2, xml_decl => 0);
418 =>
419 <root>
420 <item count="1"/>
421 <item count="2"/>
422 <item count="3"/>
423 </root>
424
425 This can be used to generate a large XML using minimum memory, example with DBI:
426
427 my $sth = $dbh->prepare('SELECT * FROM foo WHERE bar=?');
428 $sth->execute(...);
429 my $o = bless {}, 'Iterator';
430 *Iterator::iternext = sub { $sth->fetchrow_hashref() };
431 open(my $fh, '>', 'data.xml');
432 hash2xml({ row => $o }, use_attr => 1, indent => 2, xml_decl => 0, output => $fh);
433 =>
434 <root>
435 <row bar="..." ... />
436 <row bar="..." ... />
437 ...
438 </root>
439
440 =back
441
442 =head1 BENCHMARK
443
444 Performance benchmark in comparison with some popular modules(hash2xml):
445
446 Rate XML::Hash XML::Hash::LX XML::Simple XML::Hash::XS
447 XML::Hash 65.0/s -- -6% -37% -99%
448 XML::Hash::LX 68.8/s 6% -- -33% -99%
449 XML::Simple 103/s 58% 49% -- -98%
450 XML::Hash::XS 4879/s 7404% 6988% 4658% --
451
452 Benchmark was done on L<http://search.cpan.org/uploads.rdf>
453
454 =head1 AUTHOR
455
456 Yuriy Ustushenko, E<lt>[email protected]<gt>
457
458 =head1 COPYRIGHT AND LICENSE
459
460 Copyright (C) 2012-2021 Yuriy Ustushenko
461
462 This library is free software; you can redistribute it and/or modify
463 it under the same terms as Perl itself.
464
465 =cut