Writer.pm

filter: Statementstmt 96.1% 150 / 156 Branchbran 83.3% 30 / 36 Conditioncond 66.6% 18 / 27 MC/DCmcdc 46.6% 7 / 15 Subroutinesub 92.1% 35 / 38 Podpod 88.8% 8 / 9 totaltotal 88.2% 248 / 281 SCAR 34.3
CC
30
Cov
90%
new
11.0
setConsumer
9.0
new
5.2
CRAP 30.8
« Writer/XML.pm ↑ Summary
1 package XML::SAX::Writer;
2 4 $XML::SAX::Writer::VERSION = '0.56';
3 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use vars qw(%DEFAULT_ESCAPE %COMMENT_ESCAPE);
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 # ABSTRACT: SAX2 XML Writer
7  
8 4 ▶use Encode qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 ▶use XML::SAX::Exception qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 4 ▶use XML::SAX::Writer::XML qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 4 ▶use XML::Filter::BufferText qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 4 @XML::SAX::Writer::Exception::ISA = qw(XML::SAX::Exception);
13  
14  
15 4 %DEFAULT_ESCAPE = (
16 '&' => '&',
17 '<' => '&lt;',
18 '>' => '&gt;',
19 '"' => '&quot;',
20 "'" => '&apos;',
21 );
22  
23 4 %COMMENT_ESCAPE = (
24 '--' => '&#45;&#45;',
25 );
26  
27  
28 #-------------------------------------------------------------------#
29 # new
30 #-------------------------------------------------------------------#
31 sub new {
32 7 ▶ my $class = ref($_[0]) ? ref(shift) : shift;
Subroutine new: called CC=11 SCAR=24.0
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 0 7 7
33 7 ▶ my $opt = (@_ == 1) ? { %{shift()} } : {@_};
Branch: 1 branch
BranchTrueFalseTotal
@_ == 1 ? : 4 3 7
34  
35 # default the options
36 7 ▶ $opt->{Writer} ||= 'XML::SAX::Writer::XML';
Condition50%1/2
$opt->{"Writer"} ||= "XML::SAX::Writer::XML"
l!l
07
MC/DC0%0/1
$opt->{"Writer"} ||= "XML::SAX::Writer::XML"
$opt->{"Writer"}
Truth table50%1/2
A
A= $opt->{"Writer"}
Aresult
11
00
37 7 ▶ $opt->{Escape} ||= \%DEFAULT_ESCAPE;
Condition100%2/2
$opt->{"Escape"} ||= \%XML::SAX::Writer::DEFAULT_ESCAPE
l!l
16
MC/DC100%1/1
$opt->{"Escape"} ||= \%XML::SAX::Writer::DEFAULT_ESCAPE
$opt->{"Escape"}
Truth table100%2/2
A
A= $opt->{"Escape"}
Aresult
11
00
38 7 ▶ $opt->{CommentEscape} ||= \%COMMENT_ESCAPE;
Condition50%1/2
$opt->{"CommentEscape"} ||= \%XML::SAX::Writer::COMMENT_ESCAPE
l!l
07
MC/DC0%0/1
$opt->{"CommentEscape"} ||= \%XML::SAX::Writer::COMMENT_ESCAPE
$opt->{"CommentEscape"}
Truth table50%1/2
A
A= $opt->{"CommentEscape"}
Aresult
11
00
39 7 ▶ $opt->{EncodeFrom} = exists $opt->{EncodeFrom} ? $opt->{EncodeFrom} : 'utf-8';
Branch: 1 branch
BranchTrueFalseTotal
exists $opt->{'EncodeFrom'} ? : 4 3 7
40 7 ▶ $opt->{EncodeTo} = exists $opt->{EncodeTo} ? $opt->{EncodeTo} : 'utf-8';
Branch: 1 branch
BranchTrueFalseTotal
exists $opt->{'EncodeTo'} ? : 4 3 7
41 7 ▶ $opt->{Format} ||= {}; # needs options w/ defaults, we'll see later
Condition100%2/2
$opt->{"Format"} ||= {}
l!l
16
MC/DC100%1/1
$opt->{"Format"} ||= {}
$opt->{"Format"}
Truth table100%2/2
A
A= $opt->{"Format"}
Aresult
11
00
42 7 ▶ $opt->{Output} ||= *{STDOUT}{IO};
Condition100%2/2
$opt->{"Output"} ||= *STDOUT{"IO"}
l!l
52
MC/DC100%1/1
$opt->{"Output"} ||= *STDOUT{"IO"}
$opt->{"Output"}
Truth table100%2/2
A
A= $opt->{"Output"}
Aresult
11
00
43 7 ▶ $opt->{QuoteCharacter} ||= q['];
Condition100%2/2
$opt->{"QuoteCharacter"} ||= "'"
l!l
16
MC/DC100%1/1
$opt->{"QuoteCharacter"} ||= "'"
$opt->{"QuoteCharacter"}
Truth table100%2/2
A
A= $opt->{"QuoteCharacter"}
Aresult
11
00
44  
45 7 ▶ eval "use $opt->{Writer};";
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
46  
47 7 my $obj = bless $opt, $opt->{Writer};
48 7 $obj->init;
49  
50 # we need to buffer the text to escape it right
51 7 my $bf = XML::Filter::BufferText->new( Handler => $obj );
52  
53 7 return $bf;
54 }
55 #-------------------------------------------------------------------#
56  
57 #-------------------------------------------------------------------#
58 # init
59 #-------------------------------------------------------------------#
60 ▶sub init {} # noop, for subclasses
Subroutine init: called CC=1 SCAR=0.0
Pod documented
61 #-------------------------------------------------------------------#
62  
63 #-------------------------------------------------------------------#
64 # setConverter
65 #-------------------------------------------------------------------#
66 sub setConverter {
67 13 ▶ my $self = shift;
Subroutine setConverter: called CC=2 SCAR=6.9
Pod documented
68  
69 13 ▶ if (lc($self->{EncodeFrom}) ne lc($self->{EncodeTo})) {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $self->{'EncodeFrom'} ne lc $self->{'EncodeTo'}) { } 10 3 13
70 10 $self->{Encoder} = XML::SAX::Writer::Encode->new($self->{EncodeFrom}, $self->{EncodeTo});
71 }
72 else {
73 3 $self->{Encoder} = XML::SAX::Writer::NullConverter->new;
74 }
75 13 return $self;
76 }
77 #-------------------------------------------------------------------#
78  
79 #-------------------------------------------------------------------#
80 # setConsumer
81 #-------------------------------------------------------------------#
82 sub setConsumer {
83 13 ▶ my $self = shift;
Subroutine setConsumer: called CC=9 SCAR=22.0
Pod documented
84  
85 # create the Consumer
86 13 my $ref = ref $self->{Output};
87 13 ▶ if ($ref eq 'SCALAR') {
Branch: 6 branches
BranchTrueFalseTotal
if ($ref eq 'SCALAR') { } 3 10 13
elsif ($ref eq 'CODE') { } 1 9 10
elsif ($ref eq 'ARRAY') { } 1 8 9
elsif ($ref eq 'GLOB' or UNIVERSAL::isa(\$self->{'Output'}, 'GLOB') or UNIVERSAL::isa($self->{'Output'}, 'IO::Handle')) { } 4 4 8
elsif (not $ref) { } 1 3 4
elsif (UNIVERSAL::can($self->{'Output'}, 'output')) { } 2 1 3
88 3 $self->{Consumer} = XML::SAX::Writer::StringConsumer->new($self->{Output});
89 }
90 elsif ($ref eq 'CODE') {
91 1 $self->{Consumer} = XML::SAX::Writer::CodeConsumer->new($self->{Output});
92 }
93 elsif ($ref eq 'ARRAY') {
94 1 $self->{Consumer} = XML::SAX::Writer::ArrayConsumer->new($self->{Output});
95 }
96 ▶ elsif (
Condition83%5/6
$ref eq "GLOB" or UNIVERSAL::isa(\$self->{"Output"}, "GLOB") or UNIVERSAL::isa($self->{"Output"}, "IO::Handle")
l!l&&r!l&&!r
134
$ref eq "GLOB" or UNIVERSAL::isa(\$self->{"Output"}, "GLOB")
l!l&&r!l&&!r
017
MC/DC66%2/3
$ref eq "GLOB" or UNIVERSAL::isa(\$self->{"Output"}, "GLOB") or UNIVERSAL::isa($self->{"Output"}, "IO::Handle")
$ref eq "GLOB" UNIVERSAL::isa(\$self->{"Output"}, "GLOB") UNIVERSAL::isa($self->{"Output"}, "IO::Handle")
Truth table75%3/4
A or B or C
A= $ref eq "GLOB"B= UNIVERSAL::isa(\$self->{"Output"}, "GLOB")C= UNIVERSAL::isa($self->{"Output"}, "IO::Handle")
ABCresult
1XX1
01X1
0011
0000
97 $ref eq 'GLOB' or
98 UNIVERSAL::isa(\$self->{Output}, 'GLOB') or
99 UNIVERSAL::isa($self->{Output}, 'IO::Handle')) {
100 4 $self->{Consumer} = XML::SAX::Writer::HandleConsumer->new($self->{Output});
101 }
102 elsif (not $ref) {
103 1 $self->{Consumer} = XML::SAX::Writer::FileConsumer->new($self->{Output});
104 }
105 elsif (UNIVERSAL::can($self->{Output}, 'output')) {
106 2 $self->{Consumer} = $self->{Output};
107 }
108 else {
109 1 XML::SAX::Writer::Exception->throw( Message => 'Unknown option for Output' );
110 }
111 12 return $self;
112 }
113 #-------------------------------------------------------------------#
114  
115 #-------------------------------------------------------------------#
116 # setEscaperRegex
117 #-------------------------------------------------------------------#
118 sub setEscaperRegex {
119 13 ▶ my $self = shift;
Subroutine setEscaperRegex: called CC=1 SCAR=0.0
Pod documented
120  
121 $self->{EscaperRegex} = eval 'qr/' .
122 13 join( '|', map { $_ = "\Q$_\E" } keys %{$self->{Escape}}) .
123 '/;' ;
124 13 return $self;
125 }
126 #-------------------------------------------------------------------#
127  
128 #-------------------------------------------------------------------#
129 # setCommentEscaperRegex
130 #-------------------------------------------------------------------#
131 sub setCommentEscaperRegex {
132 13 ▶ my $self = shift;
Subroutine setCommentEscaperRegex: called CC=1 SCAR=0.0
Pod documented
133  
134 $self->{CommentEscaperRegex} =
135 eval 'qr/' .
136 13 join( '|', map { $_ = "\Q$_\E" } keys %{$self->{CommentEscape}}) .
137 '/;' ;
138 13 return $self;
139 }
140 #-------------------------------------------------------------------#
141  
142 #-------------------------------------------------------------------#
143 # escape
144 #-------------------------------------------------------------------#
145 sub escape {
146 3 ▶ my $self = shift;
Subroutine escape: called CC=1 SCAR=0.0
Pod documented
147 3 my $str = shift;
148  
149 3 $str =~ s/($self->{EscaperRegex})/$self->{Escape}->{$1}/ge;
150 3 return $str;
151 }
152 #-------------------------------------------------------------------#
153  
154 #-------------------------------------------------------------------#
155 # escapeComment
156 #-------------------------------------------------------------------#
157 sub escapeComment {
158 0 ▶ my $self = shift;
Subroutine escapeComment: not called CC=1 SCAR=6.9
Pod documented
159 0 my $str = shift;
160  
161 0 $str =~ s/($self->{CommentEscaperRegex})/$self->{CommentEscape}->{$1}/ge;
162 0 return $str;
163 }
164 #-------------------------------------------------------------------#
165  
166 #-------------------------------------------------------------------#
167 # convert and checking the return value
168 #-------------------------------------------------------------------#
169 sub safeConvert {
170 8 ▶ my $self = shift;
Subroutine safeConvert: called CC=3 SCAR=11.0
Pod undocumented
171 8 my $str = shift;
172  
173 8 my $out = $self->{Encoder}->convert($str);
174  
175 8 ▶ if (!defined $out && defined $str) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $out and defined $str) 1 7 8
Condition66%2/3
not defined $out and defined $str
!ll&&!rl&&r
701
MC/DC50%1/2
not defined $out and defined $str
not defined $out defined $str
Truth table66%2/3
not(A) and B
A= not defined $outB= defined $str
ABresult
0X0
100
111
176 1 warn "Conversion error returned by Encoder [$self->{Encoder}], string: '$str'";
177 1 $out = '_LOST_DATA_';
178 }
179 8 return $out;
180 }
181 #-------------------------------------------------------------------#
182  
183  
184 #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,#
185 #`,`, The Empty Consumer ,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,#
186 #```````````````````````````````````````````````````````````````````#
187  
188 # this package is only there to provide a smooth upgrade path in case
189 # new methods are added to the interface
190  
191 package XML::SAX::Writer::ConsumerInterface;
192 4 $XML::SAX::Writer::ConsumerInterface::VERSION = '0.56';
193 sub new {
194 15 ▶ my $class = shift;
Subroutine new: called CC=2 SCAR=7.6
195 15 my $ref = shift;
196 ## $self is a reference to the reference that we will send output
197 ## to. This allows us to bless $self without blessing $$self.
198 15 ▶ return bless \$ref, ref $class || $class;
Condition33%1/3
ref $class || $class
l!l&&r!l&&!r
0150
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table33%1/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
199 }
200  
201 ▶sub output {}
Subroutine output: not called CC=1 SCAR=0.0
202 ▶sub finalize {}
Subroutine finalize: called CC=1 SCAR=0.0
203  
204  
205 #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,#
206 #`,`, The String Consumer `,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,#
207 #```````````````````````````````````````````````````````````````````#
208  
209 package XML::SAX::Writer::StringConsumer;
210 4 $XML::SAX::Writer::StringConsumer::VERSION = '0.56';
211 4 @XML::SAX::Writer::StringConsumer::ISA = qw(XML::SAX::Writer::ConsumerInterface);
212  
213 #-------------------------------------------------------------------#
214 # new
215 #-------------------------------------------------------------------#
216 sub new {
217 4 ▶ my $self = shift->SUPER::new( @_ );
Subroutine new: called CC=1 SCAR=0.0
218 4 ${${$self}} = '';
219 4 return $self;
220 }
221 #-------------------------------------------------------------------#
222  
223 #-------------------------------------------------------------------#
224 # output
225 #-------------------------------------------------------------------#
226 7 ▶sub output { ${${$_[0]}} .= $_[1] }
Subroutine output: called CC=1 SCAR=0.0
227 #-------------------------------------------------------------------#
228  
229 #-------------------------------------------------------------------#
230 # finalize
231 #-------------------------------------------------------------------#
232 3 ▶sub finalize { ${$_[0]} }
Subroutine finalize: called CC=1 SCAR=0.0
233 #-------------------------------------------------------------------#
234  
235 #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,#
236 #`,`, The Code Consumer `,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,#
237 #```````````````````````````````````````````````````````````````````#
238  
239 package XML::SAX::Writer::CodeConsumer;
240 4 $XML::SAX::Writer::CodeConsumer::VERSION = '0.56';
241 4 @XML::SAX::Writer::CodeConsumer::ISA = qw(XML::SAX::Writer::ConsumerInterface );
242  
243 #-------------------------------------------------------------------#
244 # new
245 #-------------------------------------------------------------------#
246 sub new {
247 1 ▶ my $self = shift->SUPER::new( @_ );
Subroutine new: called CC=1 SCAR=0.0
248 1 $$self->( 'start_document', '' );
249 1 return $self;
250 }
251 #-------------------------------------------------------------------#
252  
253 #-------------------------------------------------------------------#
254 # output
255 #-------------------------------------------------------------------#
256 1 ▶sub output { ${$_[0]}->('data', pop) } ## Avoid an extra copy
Subroutine output: called CC=1 SCAR=0.0
257 #-------------------------------------------------------------------#
258  
259 #-------------------------------------------------------------------#
260 # finalize
261 #-------------------------------------------------------------------#
262 1 ▶sub finalize { ${$_[0]}->('end_document', '') }
Subroutine finalize: called CC=1 SCAR=0.0
263 #-------------------------------------------------------------------#
264  
265  
266 #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,#
267 #`,`, The Array Consumer ,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,#
268 #```````````````````````````````````````````````````````````````````#
269  
270 package XML::SAX::Writer::ArrayConsumer;
271 4 $XML::SAX::Writer::ArrayConsumer::VERSION = '0.56';
272 4 @XML::SAX::Writer::ArrayConsumer::ISA = qw(XML::SAX::Writer::ConsumerInterface);
273  
274 #-------------------------------------------------------------------#
275 # new
276 #-------------------------------------------------------------------#
277 sub new {
278 2 ▶ my $self = shift->SUPER::new( @_ );
Subroutine new: called CC=1 SCAR=0.0
279 2 @$$self = ();
280 2 return $self;
281 }
282 #-------------------------------------------------------------------#
283  
284 #-------------------------------------------------------------------#
285 # output
286 #-------------------------------------------------------------------#
287 2 ▶sub output { push @${$_[0]}, pop }
Subroutine output: called CC=1 SCAR=0.0
288 #-------------------------------------------------------------------#
289  
290 #-------------------------------------------------------------------#
291 # finalize
292 #-------------------------------------------------------------------#
293 1 ▶sub finalize { return ${$_[0]} }
Subroutine finalize: called CC=1 SCAR=0.0
294 #-------------------------------------------------------------------#
295  
296  
297 #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,#
298 #`,`, The Handle Consumer `,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,#
299 #```````````````````````````````````````````````````````````````````#
300  
301 package XML::SAX::Writer::HandleConsumer;
302 4 $XML::SAX::Writer::HandleConsumer::VERSION = '0.56';
303 4 @XML::SAX::Writer::HandleConsumer::ISA = qw(XML::SAX::Writer::ConsumerInterface);
304  
305 #-------------------------------------------------------------------#
306 # output
307 #-------------------------------------------------------------------#
308 sub output {
309 4 ▶ my $fh = ${$_[0]};
Subroutine output: called CC=2 SCAR=7.1
310 4 ▶ print $fh pop or XML::SAX::Exception->throw(
Branch: 1 branch
BranchTrueFalseTotal
print $fh pop() or "XML::SAX::Exception"->throw("Message", "Could not write to handle: $fh ($!)") 0 4 4
311 Message => "Could not write to handle: $fh ($!)"
312 );
313 }
314 #-------------------------------------------------------------------#
315  
316 #-------------------------------------------------------------------#
317 # finalize
318 #-------------------------------------------------------------------#
319 0 ▶sub finalize { return 0 }
Subroutine finalize: not called CC=1 SCAR=6.9
320 #-------------------------------------------------------------------#
321  
322  
323 #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,#
324 #`,`, The File Consumer `,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,#
325 #```````````````````````````````````````````````````````````````````#
326  
327 package XML::SAX::Writer::FileConsumer;
328 4 $XML::SAX::Writer::FileConsumer::VERSION = '0.56';
329 4 @XML::SAX::Writer::FileConsumer::ISA = qw(XML::SAX::Writer::HandleConsumer);
330  
331 #-------------------------------------------------------------------#
332 # new
333 #-------------------------------------------------------------------#
334 sub new {
335 3 ▶ my ( $proto, $file ) = ( shift, shift );
Subroutine new: called CC=4 SCAR=16.4
336  
337 3 ▶ XML::SAX::Writer::Exception->throw(
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file 0 3 3
Condition0%0/3
$proto || $proto
l!l&&r!l&&!r
000
MC/DC0%0/2
$proto || $proto
$proto $proto
Truth table0%0/3
A || B
A= $protoB= $proto
ABresult
1X1
011
000
338 Message => "No filename provided to " . ref( $proto || $proto )
339 ) unless defined $file;
340  
341 3 local *XFH;
342  
343 3 ▶ open XFH, ">$file" or XML::SAX::Writer::Exception->throw(
Branch: 1 branch
BranchTrueFalseTotal
open XFH, ">$file" or "XML::SAX::Writer::Exception"->throw("Message", "Error opening file ${file}: $!") 0 3 3
344 Message => "Error opening file $file: $!"
345 );
346  
347 3 return $proto->SUPER::new( *{XFH}{IO}, @_ );
348 }
349 #-------------------------------------------------------------------#
350  
351 #-------------------------------------------------------------------#
352 # finalize
353 #-------------------------------------------------------------------#
354 sub finalize {
355 2 ▶ close ${$_[0]};
Subroutine finalize: called CC=1 SCAR=0.0
356 2 return 0;
357 }
358 #-------------------------------------------------------------------#
359  
360  
361 #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,#
362 #`,`, Noop Converter ,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,#
363 #```````````````````````````````````````````````````````````````````#
364  
365 package XML::SAX::Writer::NullConverter;
366 4 $XML::SAX::Writer::NullConverter::VERSION = '0.56';
367 4 ▶sub new { return bless [], __PACKAGE__ }
Subroutine new: called CC=1 SCAR=0.0
368 3 ▶sub convert { $_[1] }
Subroutine convert: called CC=1 SCAR=0.0
369  
370  
371 #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,#
372 #`,`, Encode Converter ,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,#
373 #```````````````````````````````````````````````````````````````````#
374  
375 package XML::SAX::Writer::Encode;
376 4 $XML::SAX::Writer::Encode::VERSION = '0.56';
377 sub new {
378 11 ▶ my ($class, $from, $to) = @_;
Subroutine new: called CC=1 SCAR=0.0
379 11 my $self = {
380 from_enc => $from,
381 to_enc => $to,
382 };
383 11 return bless $self, $class;
384 }
385 sub convert {
386 7 ▶ my ($self, $data) = @_;
Subroutine convert: called CC=4 SCAR=14.0
387 7 eval {
388 7 ▶ $data = Encode::decode($self->{from_enc}, $data) if $self->{from_enc};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"from_enc"} 7 0 7
389 7 ▶ $data = Encode::encode($self->{to_enc}, $data, Encode::FB_CROAK) if $self->{to_enc};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"to_enc"} 7 0 7
390 };
391 7 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 6 7
392 1 warn $@;
393 1 return;
394 }
395 6 return $data;
396 };
397  
398  
399 4 1;
400  
401 =pod
402  
403 =encoding UTF-8
404  
405 =head1 NAME
406  
407 XML::SAX::Writer - SAX2 XML Writer
408  
409 =head1 VERSION
410  
411 version 0.56
412  
413 =head1 SYNOPSIS
414  
415 use XML::SAX::Writer;
416 use XML::SAX::SomeDriver;
417  
418 my $w = XML::SAX::Writer->new;
419 my $d = XML::SAX::SomeDriver->new(Handler => $w);
420  
421 $d->parse('some options...');
422  
423 =head1 DESCRIPTION
424  
425 =head2 Why yet another XML Writer ?
426  
427 A new XML Writer was needed to match the SAX2 effort because quite
428 naturally no existing writer understood SAX2. My first intention had
429 been to start patching XML::Handler::YAWriter as it had previously
430 been my favourite writer in the SAX1 world.
431  
432 However the more I patched it the more I realised that what I thought
433 was going to be a simple patch (mostly adding a few event handlers and
434 changing the attribute syntax) was turning out to be a rewrite due to
435 various ideas I'd been collecting along the way. Besides, I couldn't
436 find a way to elegantly make it work with SAX2 without breaking the
437 SAX1 compatibility which people are probably still using. There are of
438 course ways to do that, but most require user interaction which is
439 something I wanted to avoid.
440  
441 So in the end there was a new writer. I think it's in fact better this
442 way as it helps keep SAX1 and SAX2 separated.
443  
444 =head1 METHODS
445  
446 =over 4
447  
448 =item * new(%hash)
449  
450 This is the constructor for this object. It takes a number of
451 parameters, all of which are optional.
452  
453 =item * Output
454  
455 This parameter can be one of several things. If it is a simple
456 scalar, it is interpreted as a filename which will be opened for
457 writing. If it is a scalar reference, output will be appended to this
458 scalar. If it is an array reference, output will be pushed onto this
459 array as it is generated. If it is a filehandle, then output will be
460 sent to this filehandle.
461  
462 Finally, it is possible to pass an object for this parameter, in which
463 case it is assumed to be an object that implements the consumer
464 interface L<described later in the documentation|/THE CONSUMER
465 INTERFACE>.
466  
467 If this parameter is not provided, then output is sent to STDOUT.
468  
469 =item * Escape
470  
471 This should be a hash reference where the keys are characters
472 sequences that should be escaped and the values are the escaped form
473 of the sequence. By default, this module will escape the ampersand
474 (&), less than (<), greater than (>), double quote ("), and apostrophe
475 ('). Note that some browsers don't support the &apos; escape used for
476 apostrophes so that you should be careful when outputting XHTML.
477  
478 If you only want to add entries to the Escape hash, you can first
479 copy the contents of %XML::SAX::Writer::DEFAULT_ESCAPE.
480  
481 =item * CommentEscape
482  
483 Comment content often needs to be escaped differently from other
484 content. This option works exactly as the previous one except that
485 by default it only escapes the double dash (--) and that the contents
486 can be copied from %XML::SAX::Writer::COMMENT_ESCAPE.
487  
488 =item * EncodeFrom
489  
490 The character set encoding in which incoming data will be provided.
491 This defaults to UTF-8, which works for US-ASCII as well.
492  
493 Set this to C<undef> if you do not wish to decode your data.
494  
495 =item * EncodeTo
496  
497 The character set encoding in which output should be encoded. Again,
498 this defaults to UTF-8.
499  
500 Set this to C<undef> if you do not with to encode your data.
501  
502 =item * QuoteCharacter
503  
504 Set the character used to quote attributes. This defaults to single quotes (')
505 for backwards compatibility.
506  
507 =back
508  
509 =head1 THE CONSUMER INTERFACE
510  
511 XML::SAX::Writer can receive pluggable consumer objects that will be
512 in charge of writing out what is formatted by this module. Setting a
513 Consumer is done by setting the Output option to the object of your
514 choice instead of to an array, scalar, or file handle as is more
515 commonly done (internally those in fact map to Consumer classes and
516 and simply available as options for your convenience).
517  
518 If you don't understand this, don't worry. You don't need it most of
519 the time.
520  
521 That object can be from any class, but must have two methods in its
522 API. It is also strongly recommended that it inherits from
523 XML::SAX::Writer::ConsumerInterface so that it will not break if that
524 interface evolves over time. There are examples at the end of
525 XML::SAX::Writer's code.
526  
527 The two methods that it needs to implement are:
528  
529 =over 4
530  
531 =item * output STRING
532  
533 (Required)
534  
535 This is called whenever the Writer wants to output a string formatted
536 in XML. Encoding conversion, character escaping, and formatting have
537 already taken place. It's up to the consumer to do whatever it wants
538 with the string.
539  
540 =item * finalize()
541  
542 (Optional)
543  
544 This is called once the document has been output in its entirety,
545 during the end_document event. end_document will in fact return
546 whatever finalize() returns, and that in turn should be returned
547 by parse() for whatever parser was invoked. It might be useful if
548 you need to provide feedback of some sort.
549  
550 =back
551  
552 Here's an example of a custom consumer. Note the extra C<$> signs in
553 front of $self; the base class is optimized for the overwhelmingly
554 common case where only one data member is required and $self is a
555 reference to that data member.
556  
557 package MyConsumer;
558  
559 @ISA = qw( XML::SAX::Writer::ConsumerInterface );
560  
561 use strict;
562  
563 sub new {
564 my $self = shift->SUPER::new( my $output );
565  
566 $$self = ''; # Note the extra '$'
567  
568 return $self;
569 }
570  
571 sub output {
572 my $self = shift;
573 $$self .= uc shift;
574 }
575  
576 sub get_output {
577 my $self = shift;
578 return $$self;
579 }
580  
581 And here is one way to use it:
582  
583 my $c = MyConsumer->new;
584 my $w = XML::SAX::Writer->new( Output => $c );
585  
586 ## ... send events to $w ...
587  
588 print $c->get_output;
589  
590 If you need to store more that one data member, pass in an array or hash
591 reference:
592  
593 my $self = shift->SUPER::new( {} );
594  
595 and access it like:
596  
597 sub output {
598 my $self = shift;
599 $$self->{Output} .= uc shift;
600 }
601  
602 =head1 THE ENCODER INTERFACE
603  
604 Encoders can be plugged in to allow one to use one's favourite encoder
605 object. Presently there are two encoders: Encode and NullEncoder. They
606 need to implement two methods, and may inherit from
607 XML::SAX::Writer::NullConverter if they wish to
608  
609 =over 4
610  
611 =item new FROM_ENCODING, TO_ENCODING
612  
613 Creates a new Encoder. The arguments are the chosen encodings.
614  
615 =item convert STRING
616  
617 Converts that string and returns it.
618  
619 =back
620  
621 Note that the return value of the convert method is B<not> checked. Output may
622 be truncated if a character couldn't be converted correctly. To avoid problems
623 the encoder should take care encoding errors itself, for example by raising an
624 exception.
625  
626 =head1 CUSTOM OUTPUT
627  
628 This module is generally used to write XML -- which it does most of the
629 time -- but just like the rest of SAX it can be used as a generic
630 framework to output data, the opposite of a non-XML SAX parser.
631  
632 Of course there's only so much that one can abstract, so depending on
633 your format this may or may not be useful. If it is, you'll need to
634 know the following API (and probably to have a look inside
635 C<XML::SAX::Writer::XML>, the default Writer).
636  
637 =over
638  
639 =item init
640  
641 Called before the writing starts, it's a chance for the subclass to do
642 some initialisation if it needs it.
643  
644 =item setConverter
645  
646 This is used to set the proper converter for character encodings. The
647 default implementation should suffice but you can override it. It must
648 set C<< $self->{Encoder} >> to an Encoder object. Subclasses *should* call
649 it.
650  
651 =item setConsumer
652  
653 Same as above, except that it is for the Consumer object, and that it
654 must set C<< $self->{Consumer} >>.
655  
656 =item setEscaperRegex
657  
658 Will initialise the escaping regex C<< $self->{EscaperRegex} >> based on
659 what is needed.
660  
661 =item escape STRING
662  
663 Takes a string and escapes it properly.
664  
665 =item setCommentEscaperRegex and escapeComment STRING
666  
667 These work exactly the same as the two above, except that they are meant
668 to operate on comment contents, which often have different escaping rules
669 than those that apply to regular content.
670  
671 =back
672  
673 =head1 TODO
674  
675 - proper UTF-16 handling
676  
677 - the formatting options need to be developed.
678  
679 - test, test, test (and then some tests)
680  
681 - doc, doc, doc (actually this part is in better shape)
682  
683 - remove the xml_decl and replace it with intelligent logic, as
684 discussed on perl-xml
685  
686 - make a the Consumer selecting code available in the API, to avoid
687 duplicating
688  
689 - add an Apache output Consumer, triggered by passing $r as Output
690  
691 =head1 CREDITS
692  
693 Michael Koehne (XML::Handler::YAWriter) for much inspiration and Barrie
694 Slaymaker for the Consumer pattern idea, the coderef output option and
695 miscellaneous bugfixes and performance tweaks. Of course the usual
696 suspects (Kip Hampton and Matt Sergeant) helped in the usual ways.
697  
698 =head1 SEE ALSO
699  
700 XML::SAX::*
701  
702 =head1 AUTHORS
703  
704 =over 4
705  
706 =item *
707  
708 Robin Berjon <robin@knowscape.com>
709  
710 =item *
711  
712 Chris Prather <chris@prather.org>
713  
714 =back
715  
716 =head1 COPYRIGHT AND LICENSE
717  
718 This software is copyright (c) 2014 by Robin Berjon.
719  
720 This is free software; you can redistribute it and/or modify it under
721 the same terms as the Perl 5 programming language system itself.
722  
723 =cut
724  
725 __END__
« Writer/XML.pm ↑ Summary