CAB/Format/XmlPerl.pm untested

filter: Statementstmt 0.0% 0 / 99 Branchbran 0.0% 0 / 26 Conditioncond 0.0% 0 / 12 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 180 CC 14 SCAR 32.9
CC
14
Cov
0%
parseNode
90.0
xmlSentenceNode
12.0
parseDocument
6.0
CRAP 26.9
1 ## -*- Mode: CPerl -*-
2 ##
3 ## File: DTA::CAB::Format::XmlPerl.pm
4 ## Author: Bryan Jurish <moocow@cpan.org>
5 ## Description: Datum parser|formatter: XML (perl-near)
6  
7 package DTA::CAB::Format::XmlPerl;
8 use DTA::CAB::Format::XmlCommon;
9 use DTA::CAB::Datum ':all';
10 use DTA::CAB::Utils ':libxml';
11 use XML::LibXML;
12 use IO::File;
13 use Carp;
14 use strict;
15  
16 ##==============================================================================
17 ## Globals
18 ##==============================================================================
19  
20 our @ISA = qw(DTA::CAB::Format::XmlCommon);
21  
22 BEGIN {
23 DTA::CAB::Format->registerFormat(name=>__PACKAGE__, filenameRegex=>qr/\.(?i:xml(?:\-?)perl|perl(?:[\-\.]?)xml)$/);
24 DTA::CAB::Format->registerFormat(name=>__PACKAGE__, short=>$_) foreach (qw(xml-perl xml_perl));
25 }
26  
27 ##==============================================================================
28 ## Constructors etc.
29 ##==============================================================================
30  
31 ## $fmt = CLASS_OR_OBJ->new(%args)
32 ## + object structure: assumed HASH
33 ## (
34 ## ##-- input
35 ## xdoc => $xdoc, ##-- XML::LibXML::Document
36 ## xprs => $xprs, ##-- XML::LibXML parser
37 ##
38 ## ##-- output
39 ## #encoding => $inputEncoding, ##-- default: UTF-8; applies to output only!
40 ## level => $level, ##-- output formatting level (default=0)
41 ## hashElt => $elt, ##-- output hash element (default='map')
42 ## listElt => $elt, ##-- ouput list element (default='list')
43 ## atomElt => $elt, ##-- ouput atom element (default='val')
44 ##
45 ## ##-- common
46 ## )
47 sub new {
48 my $that = shift;
49 return $that->SUPER::new(
50 ##-- input
51 #xdoc => undef,
52 xprs => libxml_parser(keep_blanks=>0),
53  
54 ##-- output
55 level => 0,
56  
57 hashElt => 'm',
58 listElt => 'l',
59 atomElt => 'a',
60  
61 ##-- common
62  
63 ##-- user args
64 @_
65 );
66 }
67  
68 ##==============================================================================
69 ## Methods: Persistence
70 ##==============================================================================
71  
72 ## @keys = $class_or_obj->noSaveKeys()
73 ## + returns list of keys not to be saved
74 ## + inherited from XmlCommon
75  
76  
77 ##=============================================================================
78 ## Methods: Input
79 ##==============================================================================
80  
81 ##--------------------------------------------------------------
82 ## Methods: Input: Local
83  
84 ## $obj = $fmt->parseNode($nod)
85 ## + Returns the perl object represented by the XML::LibXML::Node $nod
86 our %atomNames = map {($_=>undef)} (qw(VALUE VAL V value val v ATOM atom a), '#text');
87 our %hashNames = map {($_=>undef)} qw(HASH H hash h MAP M map m);
88 our %listNames = map {($_=>undef)} qw(ARRAY array LIST L list l);
89 our %allNames = (%atomNames,%hashNames,%listNames);
90 sub parseNode {
91 my ($fmt,$nod) = @_;
92 return undef if (!defined($nod));
93 my $nodname = $nod->nodeName;
94 my ($val,$ref);
95 if (exists($atomNames{$nodname})) {
96 ##-- non-reference: <VALUE>$val</VALUE> or <VALUE undef="1"/> or plain text
97 $val = $nod->can('getAttribute') && $nod->getAttribute('undef') ? undef : $nod->textContent;
98 }
99 elsif (exists($hashNames{$nodname})){
100 ##-- HASH ref: <HASH ref="$ref"> ... <ENTRY key="$eltKey">defaultXmlNode($eltVal)</ENTRY> ... </HASH>
101 $ref = $nod->getAttribute('ref');
102 $val = {};
103 $val = bless($val,$ref) if ($ref && $ref ne 'HASH');
104 foreach (grep {ref($_) eq 'XML::LibXML::Element' && $_->hasAttribute('key')} $nod->childNodes) {
105 $val->{ $_->getAttribute('key') } = $fmt->parseNode($_);
106 }
107 }
108 elsif (exists($listNames{$nodname})) {
109 ##-- ARRAY ref: <ARRAY ref="$ref"> ... xmlNode($eltVal) ... </ARRAY>
110 $ref = $nod->getAttribute('ref');
111 $val = [];
112 $val = bless($val,$ref) if ($ref && $ref ne 'ARRAY');
113 foreach ($nod->childNodes) {
114 push(@$val, $fmt->parseNode($_));
115 }
116 }
117 elsif ($nodname =~ /^\#/) {
118 ;##-- special node, e.g. #cdata-section, #comment, etc.: skip
119 }
120 else {
121 $fmt->logwarn("cannot handle node with name=$nodname - skipping");
122 }
123 return $val;
124 }
125  
126 ##--------------------------------------------------------------
127 ## Methods: Input: Generic API
128  
129 ## $doc = $fmt->parseDocument()
130 ## + parses buffered XML::LibXML::Document
131 sub parseDocument {
132 my $fmt = shift;
133 if (!defined($fmt->{xdoc})) {
134 $fmt->logconfess("parseDocument(): no source document {xdoc} defined!");
135 return undef;
136 }
137 my $parsed = $fmt->parseNode($fmt->{xdoc}->documentElement);
138  
139 ##-- force document
140 return $fmt->forceDocument($parsed);
141 }
142  
143  
144 ##=============================================================================
145 ## Methods: Output
146 ##==============================================================================
147  
148 ##--------------------------------------------------------------
149 ## Methods: Output: MIME & HTTP stuff
150  
151 ## $short = $fmt->formatName()
152 ## + returns "official" short name for this format
153 ## + default just returns package suffix
154 sub shortName {
155 return 'xmlperl';
156 }
157  
158 ##--------------------------------------------------------------
159 ## Methods: Output: Local: Nodes
160  
161 ## $xmlnod = $fmt->tokenNode($tok)
162 ## + returns formatted token $tok as an XML node
163 sub tokenNode { return $_[0]->defaultXmlNode($_[1]); }
164  
165 ## $xmlnod = $fmt->sentenceNode($sent)
166 sub sentenceNode { return $_[0]->defaultXmlNode($_[1]); }
167  
168 ## $xmlnod = $fmt->documentNode($doc)
169 sub documentNode { return $_[0]->defaultXmlNode($_[1]); }
170  
171  
172 ## $body_array_node = $fmt->xmlBodyNode()
173 ## + gets or creates buffered body array node
174 sub xmlBodyNode {
175 my $fmt = shift;
176 my $root = $fmt->xmlRootNode('doc');
177 my ($body) = $root->findnodes('./*[@key="body"][last()]');
178 if (!defined($body)) {
179 $body = $root->addNewChild(undef,$fmt->{listElt});
180 $body->setAttribute('key','body');
181 }
182 return $body;
183 }
184  
185 ## $sentence_array_node = $fmt->xmlSentenceNode()
186 ## + gets or creates buffered sentence array node
187 sub xmlSentenceNode {
188 my $fmt = shift;
189 my $body = $fmt->xmlBodyNode();
190 my ($snod) = $body->findnodes('./*[@ref="DTA::CAB::Sentence"][last()]');
191 if (!defined($snod)) {
192 $snod = $body->addNewChild(undef,$fmt->{hashElt});
193 $snod->setAttribute("ref","DTA::CAB::Sentence");
194 }
195 my ($toks) = $snod->findnodes('./'.$fmt->{listElt}.'[@key="tokens"][last()]');
196 if (!defined($toks)) {
197 $toks = $body->addNewChild(undef,$fmt->{listElt});
198 $toks->setAttribute("key","tokens");
199 }
200 return $toks;
201 }
202  
203 ##--------------------------------------------------------------
204 ## Methods: Output: API
205  
206 ## $fmt = $fmt->putToken($tok)
207 sub putToken {
208 my ($fmt,$tok) = @_;
209 $fmt->xmlSentenceNode->addChild( $fmt->tokenNode($tok) );
210 return $fmt;
211 }
212  
213 ## $fmt = $fmt->putSentence($sent)
214 sub putSentence {
215 my ($fmt,$sent) = @_;
216 $fmt->xmlBodyNode->addChild( $fmt->sentenceNode($sent) );
217 return $fmt;
218 }
219  
220 ## $fmt = $fmt->putDocument($doc)
221 sub putDocument {
222 my ($fmt,$doc) = @_;
223 my $docnod = $fmt->documentNode($doc);
224 my $xdoc = $fmt->xmlDocument();
225 my ($root);
226 if (!defined($root=$xdoc->documentElement)) {
227 $xdoc->setDocumentElement($docnod);
228 } else {
229 my $body = $fmt->xmlBodyNode();
230 $body->addChild($_) foreach ($docnod->findnodes('./'.$fmt->{listElt}.'[@key="body"]/*'));
231 }
232 return $fmt;
233 }
234  
235 ## $fmt = $fmt->putData($data)
236 sub putData {
237 $_[0]->putDocument($_[1]);
238 }
239  
240  
241  
242 1; ##-- be happy
243  
244 __END__