File: Writer.pm

package info (click to toggle)
libxml-writer-perl 0.531-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 132 kB
  • ctags: 39
  • sloc: perl: 1,789; makefile: 39
file content (1568 lines) | stat: -rw-r--r-- 37,289 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
########################################################################
# Writer.pm - write an XML document.
# Copyright (c) 1999 by Megginson Technologies.
# Copyright (c) 2004, 2005 by Joseph Walton <joe@kafsemo.org>.
# No warranty.  Commercial and non-commercial use freely permitted.
#
# $Id: Writer.pm,v 1.36 2005/03/14 22:15:14 josephw Exp $
########################################################################

package XML::Writer;

require 5.004;

use strict;
use vars qw($VERSION);
use Carp;
use IO::Handle;
$VERSION = "0.531";



########################################################################
# Constructor.
########################################################################

#
# Public constructor.
#
# This actually does most of the work of the module: it defines closures
# for all of the real processing, and selects the appropriate closures
# to use based on the value of the UNSAFE parameter.  The actual methods
# are just stubs.
#
sub new {
  my ($class, %params) = (@_);

                                # If the user wants namespaces,
                                # intercept the request here; it will
                                # come back to this constructor
                                # from within XML::Writer::Namespaces::new()
  if ($params{NAMESPACES}) {
    delete $params{NAMESPACES};
    return new XML::Writer::Namespaces(%params);
  }

                                # Set up $self and basic parameters
  my $self;
  my $output;
  my $unsafe = $params{UNSAFE};
  my $newlines = $params{NEWLINES};
  my $dataMode = $params{DATA_MODE};
  my $dataIndent = $params{DATA_INDENT} || 0;

                                # If the NEWLINES parameter is specified,
                                # set the $nl variable appropriately
  my $nl = '';
  if ($newlines) {
    $nl = "\n";
  }

  my $outputEncoding = $params{ENCODING};

                                # Parse variables
  my @elementStack = ();
  my $elementLevel = 0;
  my %seen = ();

  my $hasData = 0;
  my @hasDataStack = ();
  my $hasElement = 0;
  my @hasElementStack = ();
  my $hasHeading = 0; # Does this document have anything before the first element?

  #
  # Private method to show attributes.
  #
  my $showAttributes = sub {
    my $atts = $_[0];
    my $i = 1;
    while ($atts->[$i]) {
      my $aname = $atts->[$i++];
      my $value = _escapeLiteral($atts->[$i++]);
      $value =~ s/\x{a}/\&#10\;/g;
      $output->print(" $aname=\"$value\"");
    }
  };

                                # Method implementations: the SAFE_
                                # versions perform error checking
                                # and then call the regular ones.
  my $end = sub {
    $output->print("\n");
  };

  my $SAFE_end = sub {
    if (!$seen{ELEMENT}) {
      croak("Document cannot end without a document element");
    } elsif ($elementLevel > 0) {
      croak("Document ended with unmatched start tag(s): @elementStack");
    } else {
      @elementStack = ();
      $elementLevel = 0;
      %seen = ();
      &{$end};
    }
  };

  my $xmlDecl = sub {
    my ($encoding, $standalone) = (@_);
    if ($standalone && $standalone ne 'no') {
      $standalone = 'yes';
    }

    # This line is questionable, but changing current behaviour
    # may be a bad idea. There seems to be a mismatch with the
    # documentation, though.
    $encoding ||= $outputEncoding || "UTF-8";
    $output->print("<?xml version=\"1.0\"");
    if ($encoding) {
      $output->print(" encoding=\"$encoding\"");
    }
    if ($standalone) {
      $output->print(" standalone=\"$standalone\"");
    }
    $output->print("?>\n");
    $hasHeading = 1;
  };

  my $SAFE_xmlDecl = sub {
    if ($seen{ANYTHING}) {
      croak("The XML declaration is not the first thing in the document");
    } else {
      $seen{ANYTHING} = 1;
      $seen{XMLDECL} = 1;
      &{$xmlDecl};
    }
  };

  my $pi = sub {
    my ($target, $data) = (@_);
    if ($data) {
      $output->print("<?$target $data?>");
    } else {
      $output->print("<?$target?>");
    }
    if ($elementLevel == 0) {
      $output->print("\n");
      $hasHeading = 1;
    }
  };

  my $SAFE_pi = sub {
    my ($name, $data) = (@_);
    $seen{ANYTHING} = 1;
    if (($name =~ /^xml/i) && ($name !~ /^xml-stylesheet$/i)) {
      carp("Processing instruction target begins with 'xml'");
    } 

    if ($name =~ /\?\>/ || (defined($data) && $data =~ /\?\>/)) {
      croak("Processing instruction may not contain '?>'");
    } elsif ($name =~ /\s/) {
      croak("Processing instruction name may not contain whitespace");
    } else {
      &{$pi};
    }
  };

  my $comment = sub {
    my $data = $_[0];
    $output->print("<!-- $data -->");
    if ($elementLevel == 0) {
      $output->print("\n");
      $hasHeading = 1;
    }
  };

  my $SAFE_comment = sub {
    my $data = $_[0];
    if ($data =~ /--/) {
      carp("Interoperability problem: \"--\" in comment text");
    }

    if ($data =~ /-->/) {
      croak("Comment may not contain '-->'");
    } else {
      $seen{ANYTHING} = 1;
      &{$comment};
    }
  };

  my $doctype = sub {
    my ($name, $publicId, $systemId) = (@_);
    $output->print("<!DOCTYPE $name");
    if ($publicId) {
      unless ($systemId) {
        croak("A DOCTYPE declaration with a public ID must also have a system ID");
      }
      $output->print(" PUBLIC \"$publicId\" \"$systemId\"");
    } elsif ($systemId) {
      $output->print(" SYSTEM \"$systemId\"");
    }
    $output->print(">\n");
    $hasHeading = 1;
  };

  my $SAFE_doctype = sub {
    my $name = $_[0];
    if ($seen{DOCTYPE}) {
      croak("Attempt to insert second DOCTYPE declaration");
    } elsif ($seen{ELEMENT}) {
      croak("The DOCTYPE declaration must come before the first start tag");
    } else {
      $seen{ANYTHING} = 1;
      $seen{DOCTYPE} = $name;
      &{$doctype};
    }
  };

  my $startTag = sub {
    my $name = $_[0];
    if ($dataMode && ($hasHeading || $elementLevel)) {
      $output->print("\n");
      $output->print(" " x ($elementLevel * $dataIndent));
    }
    $elementLevel++;
    push @elementStack, $name;
    $output->print("<$name");
    &{$showAttributes}(\@_);
    $output->print("$nl>");
    if ($dataMode) {
      $hasElement = 1;
      push @hasDataStack, $hasData;
      $hasData = 0;
      push @hasElementStack, $hasElement;
      $hasElement = 0;
    }
  };

  my $SAFE_startTag = sub {
    my $name = $_[0];

    _checkAttributes(\@_);

    if ($seen{ELEMENT} && $elementLevel == 0) {
      croak("Attempt to insert start tag after close of document element");
    } elsif ($elementLevel == 0 && $seen{DOCTYPE} && $name ne $seen{DOCTYPE}) {
      croak("Document element is \"$name\", but DOCTYPE is \""
            . $seen{DOCTYPE}
            . "\"");
    } elsif ($dataMode && $hasData) {
      croak("Mixed content not allowed in data mode: element $name");
    } else {
      $seen{ANYTHING} = 1;
      $seen{ELEMENT} = 1;
      &{$startTag};
    }
  };

  my $emptyTag = sub {
    my $name = $_[0];
    if ($dataMode && ($hasHeading || $elementLevel)) {
      $output->print("\n");
      $output->print(" " x ($elementLevel * $dataIndent));
    }
    $output->print("<$name");
    &{$showAttributes}(\@_);
    $output->print("$nl />");
    if ($dataMode) {
      $hasElement = 1;
    }
  };

  my $SAFE_emptyTag = sub {
    my $name = $_[0];

    _checkAttributes(\@_);

    if ($seen{ELEMENT} && $elementLevel == 0) {
      croak("Attempt to insert empty tag after close of document element");
    } elsif ($elementLevel == 0 && $seen{DOCTYPE} && $name ne $seen{DOCTYPE}) {
      croak("Document element is \"$name\", but DOCTYPE is \""
            . $seen{DOCTYPE}
            . "\"");
    } elsif ($dataMode && $hasData) {
      croak("Mixed content not allowed in data mode: element $name");
    } else {
      $seen{ANYTHING} = 1;
      $seen{ELEMENT} = 1;
      &{$emptyTag};
    }
  };

  my $endTag = sub {
    my $name = $_[0];
    my $currentName = pop @elementStack;
    $name = $currentName unless $name;
    $elementLevel--;
    if ($dataMode && $hasElement) {
      $output->print("\n");
      $output->print(" " x ($elementLevel * $dataIndent));
    }
    $output->print("</$name$nl>");
    if ($dataMode) {
      $hasData = pop @hasDataStack;
      $hasElement = pop @hasElementStack;
    }
  };

  my $SAFE_endTag = sub {
    my $name = $_[0];
    my $oldName = $elementStack[$#elementStack];
    if ($elementLevel <= 0) {
      croak("End tag \"$name\" does not close any open element");
    } elsif ($name && ($name ne $oldName)) {
      croak("Attempt to end element \"$oldName\" with \"$name\" tag");
    } else {
      &{$endTag};
    }
  };

  my $characters = sub {
    my $data = $_[0];
    if ($data =~ /[\&\<\>]/) {
      $data =~ s/\&/\&amp\;/g;
      $data =~ s/\</\&lt\;/g;
      $data =~ s/\>/\&gt\;/g;
    }
    $output->print($data);
    $hasData = 1;
  };

  my $SAFE_characters = sub {
    if ($elementLevel < 1) {
      croak("Attempt to insert characters outside of document element");
    } elsif ($dataMode && $hasElement) {
      croak("Mixed content not allowed in data mode: characters");
    } else {
      &{$characters};
    }
  };

  my $raw = sub {
    $output->print($_[0]);
    # Don't set $hasData or any other information: we know nothing
    # about what was just written.
    #
  };

  my $SAFE_raw = sub {
    croak('raw() is only available when UNSAFE is set');
  };

  my $cdata = sub {
      my $data = $_[0];
      $data    =~ s/\]\]>/\]\]\]\]><!\[CDATA\[>/g;
      $output->print("<![CDATA[$data]]>");
      $hasData = 1;
  };

  my $SAFE_cdata = sub {
    if ($elementLevel < 1) {
      croak("Attempt to insert characters outside of document element");
    } elsif ($dataMode && $hasElement) {
      croak("Mixed content not allowed in data mode: characters");
    } else {
      &{$cdata};
    }
  };

                                # Assign the correct closures based on
                                # the UNSAFE parameter
  if ($unsafe) {
    $self = {'END' => $end,
             'XMLDECL' => $xmlDecl,
             'PI' => $pi,
             'COMMENT' => $comment,
             'DOCTYPE' => $doctype,
             'STARTTAG' => $startTag,
             'EMPTYTAG' => $emptyTag,
             'ENDTAG' => $endTag,
             'CHARACTERS' => $characters,
             'RAW' => $raw,
             'CDATA' => $cdata
            };
  } else {
    $self = {'END' => $SAFE_end,
             'XMLDECL' => $SAFE_xmlDecl,
             'PI' => $SAFE_pi,
             'COMMENT' => $SAFE_comment,
             'DOCTYPE' => $SAFE_doctype,
             'STARTTAG' => $SAFE_startTag,
             'EMPTYTAG' => $SAFE_emptyTag,
             'ENDTAG' => $SAFE_endTag,
             'CHARACTERS' => $SAFE_characters,
             'RAW' => $SAFE_raw,               # This will intentionally fail
             'CDATA' => $SAFE_cdata
            };
  }

                                # Query methods
  $self->{'IN_ELEMENT'} = sub {
    my ($ancestor) = (@_);
    return $elementStack[$#elementStack] eq $ancestor;
  };

  $self->{'WITHIN_ELEMENT'} = sub {
    my ($ancestor) = (@_);
    my $el;
    foreach $el (@elementStack) {
      return 1 if $el eq $ancestor;
    }
    return 0;
  };

  $self->{'CURRENT_ELEMENT'} = sub {
    return $elementStack[$#elementStack];
  };

  $self->{'ANCESTOR'} = sub {
    my ($n) = (@_);
    return $elementStack[$#elementStack-$n];
  };

                                # Set and get the output destination.
  $self->{'GETOUTPUT'} = sub {
    return $output;
  };

  $self->{'SETOUTPUT'} = sub {
    my $newOutput = $_[0];

    if (ref($newOutput) eq 'SCALAR') {
      $newOutput = new XML::Writer::_String($newOutput);
    }
                                # If there is no OUTPUT parameter,
                                # use standard output
    $output = $newOutput || \*STDOUT;
    if ($outputEncoding) {
      if (lc($outputEncoding) ne 'utf-8') {
        die 'The only supported encoding is utf-8';
      }
      binmode($output, ':encoding(utf-8)');
    }
  };

  $self->{'SETDATAMODE'} = sub {
    $dataMode = $_[0];
  };

  $self->{'GETDATAMODE'} = sub {
    return $dataMode;
  };

  $self->{'SETDATAINDENT'} = sub {
    $dataIndent = $_[0];
  };

  $self->{'GETDATAINDENT'} = sub {
    return $dataIndent;
  };

                                # Set the output.
  &{$self->{'SETOUTPUT'}}($params{'OUTPUT'});

                                # Return the blessed object.
  return bless $self, $class;
}



########################################################################
# Public methods
########################################################################

#
# Finish writing the document.
#
sub end {
  my $self = shift;
  &{$self->{END}};
}

#
# Write an XML declaration.
#
sub xmlDecl {
  my $self = shift;
  &{$self->{XMLDECL}};
}

#
# Write a processing instruction.
#
sub pi {
  my $self = shift;
  &{$self->{PI}};
}

#
# Write a comment.
#
sub comment {
  my $self = shift;
  &{$self->{COMMENT}};
}

#
# Write a DOCTYPE declaration.
#
sub doctype {
  my $self = shift;
  &{$self->{DOCTYPE}};
}

#
# Write a start tag.
#
sub startTag {
  my $self = shift;
  &{$self->{STARTTAG}};
}

#
# Write an empty tag.
#
sub emptyTag {
  my $self = shift;
  &{$self->{EMPTYTAG}};
}

#
# Write an end tag.
#
sub endTag {
  my $self = shift;
  &{$self->{ENDTAG}};
}

#
# Write a simple data element.
#
sub dataElement {
  my ($self, $name, $data, %atts) = (@_);
  $self->startTag($name, %atts);
  $self->characters($data);
  $self->endTag($name);
}

#
# Write a simple CDATA element.
#
sub cdataElement {
    my ($self, $name, $data, %atts) = (@_);
    $self->startTag($name, %atts);
    $self->cdata($data);
    $self->endTag($name);
}

#
# Write character data.
#
sub characters {
  my $self = shift;
  &{$self->{CHARACTERS}};
}

#
# Write raw, unquoted, completely unchecked character data.
#
sub raw {
  my $self = shift;
  &{$self->{RAW}};
}

#
# Write CDATA.
#
sub cdata {
    my $self = shift;
    &{$self->{CDATA}};
}

#
# Query the current element.
#
sub in_element {
  my $self = shift;
  return &{$self->{IN_ELEMENT}};
}

#
# Query the ancestors.
#
sub within_element {
  my $self = shift;
  return &{$self->{WITHIN_ELEMENT}};
}

#
# Get the name of the current element.
#
sub current_element {
  my $self = shift;
  return &{$self->{CURRENT_ELEMENT}};
}

#
# Get the name of the numbered ancestor (zero-based).
#
sub ancestor {
  my $self = shift;
  return &{$self->{ANCESTOR}};
}

#
# Get the current output destination.
#
sub getOutput {
  my $self = shift;
  return &{$self->{GETOUTPUT}};
}


#
# Set the current output destination.
#
sub setOutput {
  my $self = shift;
  return &{$self->{SETOUTPUT}};
}

#
# Set the current data mode (true or false).
#
sub setDataMode {
  my $self = shift;
  return &{$self->{SETDATAMODE}};
}


#
# Get the current data mode (true or false).
#
sub getDataMode {
  my $self = shift;
  return &{$self->{GETDATAMODE}};
}


#
# Set the current data indent step.
#
sub setDataIndent {
  my $self = shift;
  return &{$self->{SETDATAINDENT}};
}


#
# Get the current data indent step.
#
sub getDataIndent {
  my $self = shift;
  return &{$self->{GETDATAINDENT}};
}


#
# Empty stub.
#
sub addPrefix {
}


#
# Empty stub.
#
sub removePrefix {
}



########################################################################
# Private functions.
########################################################################

#
# Private: check for duplicate attributes.
# Note - this starts at $_[1], because $_[0] is assumed to be an
# element name.
#
sub _checkAttributes {
  my %anames;
  my $i = 1;
  while ($_[0]->[$i]) {
    my $name = $_[0]->[$i];
    $i += 2;
    if ($anames{$name}) {
      croak("Two attributes named \"$name\"");
    } else {
      $anames{$name} = 1;
    }
  }
}

#
# Private: escape an attribute value literal.
#
sub _escapeLiteral {
  my $data = $_[0];
  if ($data =~ /[\&\<\>\"]/) {
    $data =~ s/\&/\&amp\;/g;
    $data =~ s/\</\&lt\;/g;
    $data =~ s/\>/\&gt\;/g;
    $data =~ s/\"/\&quot\;/g;
  }
  return $data;
}



########################################################################
# XML::Writer::Namespaces - subclass for Namespace processing.
########################################################################

package XML::Writer::Namespaces;
use strict;
use vars qw(@ISA);
use Carp;

@ISA = qw(XML::Writer);

#
# Constructor
#
sub new {
  my ($class, %params) = (@_);

  my $unsafe = $params{UNSAFE};

                                # Snarf the prefix map, if any, and
                                # note the default prefix.
  my %prefixMap = ();
  if ($params{PREFIX_MAP}) {
    %prefixMap = (%{$params{PREFIX_MAP}});
    delete $params{PREFIX_MAP};
  }
  $prefixMap{'http://www.w3.org/XML/1998/namespace'} = 'xml';

                                # Generate the reverse map for URIs
  my $uriMap = {};
  my $key;
  foreach $key (keys(%prefixMap)) {
    $uriMap->{$prefixMap{$key}} = $key;
  }

  my $defaultPrefix = $uriMap->{''};
  delete $prefixMap{$defaultPrefix} if ($defaultPrefix);

                                # Create an instance of the parent.
  my $self = new XML::Writer(%params);

                                # Snarf the parent's methods that we're
                                # going to override.
  my $OLD_startTag = $self->{STARTTAG};
  my $OLD_emptyTag = $self->{EMPTYTAG};
  my $OLD_endTag = $self->{ENDTAG};

                                # State variables
  my @stack;
  my $prefixCounter = 1;
  my $nsDecls = {'http://www.w3.org/XML/1998/namespace' => 'xml'};
  my $nsDefaultDecl = undef;
  my $nsCopyFlag = 0;
  my @forcedNSDecls = ();

  if ($params{FORCED_NS_DECLS}) {
    @forcedNSDecls = @{$params{FORCED_NS_DECLS}};
    delete $params{FORCED_NS_DECLS};
  }

  #
  # Push the current declaration state.
  #
  my $pushState = sub {
    push @stack, [$nsDecls, $nsDefaultDecl, $nsCopyFlag, $uriMap];
    $nsCopyFlag = 0;
  };


  #
  # Pop the current declaration state.
  #
  my $popState = sub {
    ($nsDecls, $nsDefaultDecl, $nsCopyFlag, $uriMap) = @{pop @stack};
  };

  #
  # Generate a new prefix.
  #
  my $genPrefix = sub {
    my $uri = $_[0];
    my $prefixCounter = 1;
    my $prefix = $prefixMap{$uri};
    my %clashMap = %{$uriMap};
    while( my ($u, $p) = each(%prefixMap)) {
      $clashMap{$p} = $u;
    }

    while (!defined($prefix) || ($clashMap{$prefix} && $clashMap{$prefix} ne $uri)) {
      $prefix = "__NS$prefixCounter";
      $prefixCounter++;
    }

    return $prefix;
  };

  #
  # Perform namespace processing on a single name.
  #
  my $processName = sub {
    my ($nameref, $atts, $attFlag) = (@_);
    my ($uri, $local) = @{$$nameref};
    my $prefix = $nsDecls->{$uri};

                                # Is this an element name that matches
                                # the default NS?
    if (!$attFlag && $defaultPrefix && ($uri eq $defaultPrefix)) {
      unless ($nsDefaultDecl && ($nsDefaultDecl eq $uri)) {
        push @{$atts}, 'xmlns';
        push @{$atts}, $uri;
        $nsDefaultDecl = $uri;
      }
      $$nameref = $local;

      if (defined($uriMap->{''})) {
        delete ($nsDecls->{$uriMap->{''}});
      }

      $nsDecls->{$uri} = '';
      unless ($nsCopyFlag) {
        $uriMap = {%{$uriMap}};
        $nsDecls = {%{$nsDecls}};
        $nsCopyFlag = 1;
      }
      $uriMap->{''} = $uri;
      
                                # Is there a straight-forward prefix?
    } elsif ($prefix) {
      $$nameref = "$prefix:$local";
    } else {
      $prefix = &{$genPrefix}($uri);
      unless ($nsCopyFlag) {
        $uriMap = {%{$uriMap}};
        $nsDecls = {%{$nsDecls}};
        $nsCopyFlag = 1;
      }
      $uriMap->{$prefix} = $uri;
      $nsDecls->{$uri} = $prefix;
      push @{$atts}, "xmlns:$prefix";
      push @{$atts}, $uri;
      $$nameref = "$prefix:$local";
    }
  };


  #
  # Perform namespace processing on element and attribute names.
  #
  my $nsProcess = sub {
    if (ref($_[0]->[0]) eq 'ARRAY') {
      &{$processName}(\$_[0]->[0], $_[0], 0);
    }
    my $i = 1;
    while ($_[0]->[$i]) {
      if (ref($_[0]->[$i]) eq 'ARRAY') {
        &{$processName}(\$_[0]->[$i], $_[0], 1);
      }
      $i += 2;
    }

    # We do this if any declarations are forced, due either to
    #  constructor arguments or to a call during processing.
    if (@forcedNSDecls) {
      foreach (@forcedNSDecls) {
        my @dummy = ($_, 'dummy');
        my $d2 = \@dummy;
        if ($defaultPrefix && ($_ eq $defaultPrefix)) {
          &{$processName}(\$d2, $_[0], 0);
        } else {
          &{$processName}(\$d2, $_[0], 1);
        }
      }
      @forcedNSDecls = ();
    }
  };


  # Indicate that a namespace should be declared by the next open element
  $self->{FORCENSDECL} = sub {
    push @forcedNSDecls, $_[0];
  };


  #
  # Start tag, with NS processing
  #
  $self->{STARTTAG} = sub {
    my $name = $_[0];
    unless ($unsafe) {
      _checkNSNames(\@_);
    }
    &{$pushState}();
    &{$nsProcess}(\@_);
    &{$OLD_startTag};
  };


  #
  # Empty tag, with NS processing
  #
  $self->{EMPTYTAG} = sub {
    unless ($unsafe) {
      _checkNSNames(\@_);
    }
    &{$pushState}();
    &{$nsProcess}(\@_);
    &{$OLD_emptyTag};
    &{$popState}();
  };


  #
  # End tag, with NS processing
  #
  $self->{ENDTAG} = sub {
    my $name = $_[0];
    if (ref($_[0]) eq 'ARRAY') {
      my $pfx = $nsDecls->{$_[0]->[0]};
      if ($pfx) {
        $_[0] = $pfx . ':' . $_[0]->[1];
      } else {
        $_[0] = $_[0]->[1];
      }
    } else {
      $_[0] = $_[0];
    }
#    &{$nsProcess}(\@_);
    &{$OLD_endTag};
    &{$popState}();
  };


  #
  # Processing instruction, but only if not UNSAFE.
  #
  unless ($unsafe) {
    my $OLD_pi = $self->{PI};
    $self->{PI} = sub {
      my $target = $_[0];
      if (index($target, ':') >= 0) {
        croak "PI target '$target' contains a colon.";
      }
      &{$OLD_pi};
    }
  };


  #
  # Add a prefix to the prefix map.
  #
  $self->{ADDPREFIX} = sub {
    my ($uri, $prefix) = (@_);
    if ($prefix) {
      $prefixMap{$uri} = $prefix;
    } else {
      if (defined($defaultPrefix)) {
        delete($prefixMap{$defaultPrefix});
      }
      $defaultPrefix = $uri;
    }
  };


  #
  # Remove a prefix from the prefix map.
  #
  $self->{REMOVEPREFIX} = sub {
    my ($uri) = (@_);
    if ($defaultPrefix && ($defaultPrefix eq $uri)) {
      $defaultPrefix = undef;
    }
    delete $prefixMap{$uri};
  };


  #
  # Bless and return the object.
  #
  return bless $self, $class;
}


#
# Add a preferred prefix for a namespace URI.
#
sub addPrefix {
  my $self = shift;
  return &{$self->{ADDPREFIX}};
}


#
# Remove a preferred prefix for a namespace URI.
#
sub removePrefix {
  my $self = shift;
  return &{$self->{REMOVEPREFIX}};
}


#
# Check names.
#
sub _checkNSNames {
  my $names = $_[0];
  my $i = 1;
  my $name = $names->[0];

                                # Check the element name.
  if (ref($name) eq 'ARRAY') {
    if (index($name->[1], ':') >= 0) {
      croak("Local part of element name '" .
            $name->[1] .
            "' contains a colon.");
    }
  } elsif (index($name, ':') >= 0) {
    croak("Element name '$name' contains a colon.");
  }

                                # Check the attribute names.
  while ($names->[$i]) {
    my $name = $names->[$i];
    if (ref($name) eq 'ARRAY') {
      my $local = $name->[1];
      if (index($local, ':') >= 0) {
        croak "Local part of attribute name '$local' contains a colon.";
      }
    } else {
      if ($name =~ /^xmlns/) {
        croak "Attribute name '$name' begins with 'xmlns'";
      } elsif (index($name, ':') >= 0) {
        croak "Attribute name '$name' contains ':'";
      }
    }
    $i += 2;
  }
}

sub forceNSDecl
{
  my $self = shift;
  return &{$self->{FORCENSDECL}};
}


package XML::Writer::_String;

# Internal class, behaving sufficiently like an IO::Handle,
#  that stores written output in a string
#
# Heavily inspired by Simon Oliver's XML::Writer::String

sub new
{
  my $class = shift;
  my $scalar_ref = shift;
  return bless($scalar_ref, $class);
}

sub print
{
  ${(shift)} .= join('', @_);
  return 1;
}

1;
__END__

########################################################################
# POD Documentation
########################################################################

=head1 NAME

XML::Writer - Perl extension for writing XML documents.

=head1 SYNOPSIS

  use XML::Writer;
  use IO::File;

  my $output = new IO::File(">output.xml");

  my $writer = new XML::Writer(OUTPUT => $output);
  $writer->startTag("greeting", 
                    "class" => "simple");
  $writer->characters("Hello, world!");
  $writer->endTag("greeting");
  $writer->end();
  $output->close();


=head1 DESCRIPTION

XML::Writer is a helper module for Perl programs that write an XML
document.  The module handles all escaping for attribute values and
character data and constructs different types of markup, such as tags,
comments, and processing instructions.

By default, the module performs several well-formedness checks to
catch errors during output.  This behaviour can be extremely useful
during development and debugging, but it can be turned off for
production-grade code.

The module can operate either in regular mode in or Namespace
processing mode.  In Namespace mode, the module will generate
Namespace Declarations itself, and will perform additional checks on
the output.

Additional support is available for a simplified data mode with no
mixed content: newlines are automatically inserted around elements and
elements can optionally be indented based as their nesting level.


=head1 METHODS

=head2 Writing XML

=over 4

=item new([$params])

Create a new XML::Writer object:

  my $writer = new XML::Writer(OUTPUT => $output, NEWLINES => 1);

Arguments are an anonymous hash array of parameters:

=over 4

=item OUTPUT

An object blessed into IO::Handle or one of its subclasses (such as
IO::File), or a reference to a string; if this parameter is not present,
the module will write to standard output. If a string reference is passed,
it will capture the generated XML.

=item NAMESPACES

A true (1) or false (0, undef) value; if this parameter is present and
its value is true, then the module will accept two-member array
reference in the place of element and attribute names, as in the
following example:

  my $rdfns = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
  my $writer = new XML::Writer(NAMESPACES => 1);
  $writer->startTag([$rdfns, "Description"]);

The first member of the array is a namespace URI, and the second part
is the local part of a qualified name.  The module will automatically
generate appropriate namespace declarations and will replace the URI
part with a prefix.

=item PREFIX_MAP

A hash reference; if this parameter is present and the module is
performing namespace processing (see the NAMESPACES parameter), then
the module will use this hash to look up preferred prefixes for
namespace URIs:


  my $rdfns = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
  my $writer = new XML::Writer(NAMESPACES => 1,
                               PREFIX_MAP => {$rdfns => 'rdf'});

The keys in the hash table are namespace URIs, and the values are the
associated prefixes.  If there is not a preferred prefix for the
namespace URI in this hash, then the module will automatically
generate prefixes of the form "__NS1", "__NS2", etc.

To set the default namespace, use '' for the prefix.

=item FORCED_NS_DECLS

An array reference; if this parameter is present, the document element
will contain declarations for all the given namespace URIs.
Declaring namespaces in advance is particularly useful when a large
number of elements from a namespace are siblings, but don't share a direct
ancestor from the same namespace.

=item NEWLINES

A true or false value; if this parameter is present and its value is
true, then the module will insert an extra newline before the closing
delimiter of start, end, and empty tags to guarantee that the document
does not end up as a single, long line.  If the paramter is not
present, the module will not insert the newlines.

=item UNSAFE

A true or false value; if this parameter is present and its value is
true, then the module will skip most well-formedness error checking.
If the parameter is not present, the module will perform the
well-formedness error checking by default.  Turn off error checking at
your own risk!

=item DATA_MODE

A true or false value; if this parameter is present and its value is
true, then the module will enter a special data mode, inserting
newlines automatically around elements and (unless UNSAFE is also
specified) reporting an error if any element has both characters and
elements as content.

=item DATA_INDENT

A numeric value; if this parameter is present, it represents the
indent step for elements in data mode (it will be ignored when not in
data mode).

=item ENCODING

A character encoding; currently this must be exactly 'utf-8'. If present,
it will be used for the underlying character encoding and as the
default in the XML declaration.

=back

=item end()

Finish creating an XML document.  This method will check that the
document has exactly one document element, and that all start tags are
closed:

  $writer->end();

=item xmlDecl([$encoding, $standalone])

Add an XML declaration to the beginning of an XML document.  The
version will always be "1.0".  If you provide a non-null encoding or
standalone argument, its value will appear in the declaration (and
non-null value for standalone except 'no' will automatically be
converted to 'yes').

  $writer->xmlDecl("UTF-8");

=item doctype($name, [$publicId, $systemId])

Add a DOCTYPE declaration to an XML document.  The declaration must
appear before the beginning of the root element.  If you provide a
publicId, you must provide a systemId as well, but you may provide
just a system ID by passing 'undef' for the publicId.

  $writer->doctype("html");

=item comment($text)

Add a comment to an XML document.  If the comment appears outside the
document element (either before the first start tag or after the last
end tag), the module will add a carriage return after it to improve
readability:

  $writer->comment("This is a comment");

=item pi($target [, $data])

Add a processing instruction to an XML document:

  $writer->pi('xml-stylesheet', 'href="style.css" type="text/css"');

If the processing instruction appears outside the document element
(either before the first start tag or after the last end tag), the
module will add a carriage return after it to improve readability.

The $target argument must be a single XML name.  If you provide the
$data argument, the module will insert its contents following the
$target argument, separated by a single space.

=item startTag($name [, $aname1 => $value1, ...])

Add a start tag to an XML document.  Any arguments after the element
name are assumed to be name/value pairs for attributes: the module
will escape all '&', '<', '>', and '"' characters in the attribute
values using the predefined XML entities:

  $writer->startTag('doc', 'version' => '1.0',
                           'status' => 'draft',
                           'topic' => 'AT&T');

All start tags must eventually have matching end tags.

=item emptyTag($name [, $aname1 => $value1, ...])

Add an empty tag to an XML document.  Any arguments after the element
name are assumed to be name/value pairs for attributes (see startTag()
for details):

  $writer->emptyTag('img', 'src' => 'portrait.jpg',
                           'alt' => 'Portrait of Emma.');

=item endTag([$name])

Add an end tag to an XML document.  The end tag must match the closest
open start tag, and there must be a matching and properly-nested end
tag for every start tag:

  $writer->endTag('doc');

If the $name argument is omitted, then the module will automatically
supply the name of the currently open element:

  $writer->startTag('p');
  $writer->endTag();

=item dataElement($name, $data [, $aname1 => $value1, ...])

Print an entire element containing only character data.  This is
equivalent to

  $writer->startTag($name [, $aname1 => $value1, ...]);
  $writer->characters($data);
  $writer->endTag($name);

=item characters($data)

Add character data to an XML document.  All '<', '>', and '&'
characters in the $data argument will automatically be escaped using
the predefined XML entities:

  $writer->characters("Here is the formula: ");
  $writer->characters("a < 100 && a > 5");

You may invoke this method only within the document element
(i.e. after the first start tag and before the last end tag).

In data mode, you must not use this method to add whitespace between
elements.

=item raw($data)

Print data completely unquoted and unchecked to the XML document.  For
example C<raw('<')> will print a literal < character.  This
necessarily bypasses all well-formedness checking, and is therefore
only available in unsafe mode.

This can sometimes be useful for printing entities which are defined
for your XML format but the module doesn't know about, for example
&nbsp; for XHTML.

=item cdata($data)

As C<characters()> but writes the data quoted in a CDATA section, that
is, between <![CDATA[ and ]]>.  If the data to be written itself
contains ]]>, it will be written as several consecutive CDATA
sections.

=item cdataElement($name, $data [, $aname1 => $value1, ...])

As C<dataElement()> but the element content is written as one or more
CDATA sections (see C<cdata()>).

=item setOutput($output)

Set the current output destination, as in the OUTPUT parameter for the
constructor.

=item getOutput()

Return the current output destination, as in the OUTPUT parameter for
the constructor.

=item setDataMode($mode)

Enable or disable data mode, as in the DATA_MODE parameter for the
constructor.

=item getDataMode()

Return the current data mode, as in the DATA_MODE parameter for the
constructor.

=item setDataIndent($step)

Set the indent step for data mode, as in the DATA_INDENT parameter for
the constructor.

=item getDataIndent()

Return the indent step for data mode, as in the DATA_INDENT parameter
for the constructor.


=back

=head2 Querying XML

=over 4

=item in_element($name)

Return a true value if the most recent open element matches $name:

  if ($writer->in_element('dl')) {
    $writer->startTag('dt');
  } else {
    $writer->startTag('li');
  }

=item within_element($name)

Return a true value if any open element matches $name:

  if ($writer->within_element('body')) {
    $writer->startTag('h1');
  } else {
    $writer->startTag('title');
  }

=item current_element()

Return the name of the currently open element:

  my $name = $writer->current_element();

This is the equivalent of

  my $name = $writer->ancestor(0);

=item ancestor($n)

Return the name of the nth ancestor, where $n=0 for the current open
element.

=back


=head2 Additional Namespace Support

As of 0.510, these methods may be used while writing a document.

=over 4

=item addPrefix($uri, $prefix)

Add a preferred mapping between a Namespace URI and a prefix.  See
also the PREFIX_MAP constructor parameter.

To set the default namespace, omit the $prefix parameter or set it to
''.

=item removePrefix($uri)

Remove a preferred mapping between a Namespace URI and a prefix.

=item forceNSDecl($uri)

Indicate that a namespace declaration for this URI should be included
with the next element to be started.

=back


=head1 ERROR REPORTING

With the default settings, the XML::Writer module can detect several
basic XML well-formedness errors:

=over 4

=item *

Lack of a (top-level) document element, or multiple document elements.

=item *

Unclosed start tags.

=item *

Misplaced delimiters in the contents of processing instructions or
comments.

=item *

Misplaced or duplicate XML declaration(s).

=item *

Misplaced or duplicate DOCTYPE declaration(s).

=item *

Mismatch between the document type name in the DOCTYPE declaration and
the name of the document element.

=item *

Mismatched start and end tags.

=item *

Attempts to insert character data outside the document element.

=item *

Duplicate attributes with the same name.

=back

During Namespace processing, the module can detect the following
additional errors:

=over 4

=item *

Attempts to use PI targets or element or attribute names containing a
colon.

=item *

Attempts to use attributes with names beginning "xmlns".

=back

To ensure full error detection, a program must also invoke the end
method when it has finished writing a document:

  $writer->startTag('greeting');
  $writer->characters("Hello, world!");
  $writer->endTag('greeting');
  $writer->end();

This error reporting can catch many hidden bugs in Perl programs that
create XML documents; however, if necessary, it can be turned off by
providing an UNSAFE parameter:

  my $writer = new XML::Writer(OUTPUT => $output, UNSAFE => 1);


=head1 AUTHOR

David Megginson E<lt>david@megginson.comE<gt>


=head1 COPYRIGHT

Copyright 1999, 2000 David Megginson E<lt>david@megginson.comE<gt>

Copyright 2004 Joseph Walton E<lt>joe@kafsemo.orgE<gt>


=head1 SEE ALSO

XML::Parser

=cut