blib/lib/XML/XSH2/XPathToXML.pm untested

filter: Statementstmt 0.0% 0 / 216 Branchbran 0.0% 0 / 134 Conditioncond 0.0% 0 / 40 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 18 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 422 CC 68 SCAR 61.3
CC
68
Cov
0%
_createSteps
1122.0
createNode
56.0
_lookup_namespace
56.0
CRAP 458.7
1 package XML::XSH2::XPathToXML;
2 ###
3 #
4 # Name: XML::XSH2::XPathToXML
5 # Version: 0.05
6 # Description: Parses a list of XPath/value pairs and returns an XML::LibXML note-tree.
7 # Original author: Kurt George Gjerde
8 # Extended by Petr Pajas
9 # Copyright: InterMedia, University of Bergen (2002)
10 # Licence: Same as Perl
11 #
12 ###
13  
14 ### POD at bottom.
15  
16  
17 ###
18  
19 use XML::LibXML;
20 use strict;
21 no warnings qw(uninitialized);
22  
23 use vars qw($VERSION);
24 $VERSION = '0.05';
25  
26 my $PACKAGE = __PACKAGE__;
27  
28 our ($QUOT,$NAMECHAR,$FIRSTNAMECHAR,$NAME,$STEP,$LAST_STEP,$FILTER,$PREDICATE,$AXIS);
29  
30 # regexps to parse XPath steps
31  
32 $NAMECHAR = '[-_.[:alnum:]]';
33 $FIRSTNAMECHAR = '[-_.[:alpha:]]';
34 $NAME = "(?:${FIRSTNAMECHAR}${NAMECHAR}*(?::${FIRSTNAMECHAR}${NAMECHAR}+)*)";
35  
36 $QUOT = q{(?:'[^']*'|"[^"]*")};
37 $PREDICATE = qr/
38 (?:
39 (?> [^][()"']* ) # non-parens without backtracking
40 |
41 '[^']*' | "[^"]*" # quotes
42 |
43 \[
44 (??{$PREDICATE}) # matching square brackets
45 \]
46 |
47 \(
48 (??{$PREDICATE}) # matching round brackets
49 \)
50 )*
51 /x;
52  
53 $FILTER = qr/(?:\[$PREDICATE\])/;
54  
55 $AXIS=qr{(?:(?:following-sibling|following|preceding|preceding-sibling|parent|ancestor|ancestor-or-self|descendant|self|descendant-or-self|child|namespace)::)?};
56 $STEP = qr{(?:(?:^|/)${AXIS}${NAME}${FILTER}*)};
57 $LAST_STEP = qr{(?:(?:^|/)(?:\@${NAME}|${AXIS}(?:${NAME}|comment[(][)]|text[(][)]|processing-instruction[(](?:\s*"${NAME}"\s*|\s*'${NAME}'\s*)[)]))${FILTER}*)};
58  
59 ### NEW
60 #
61 sub new {
62 my ($class, %args) = @_;
63 my $self = \%args;
64 bless $self, $class;
65  
66 $self->{version} ||= '1.0';
67 $self->{debug} ||= 0;
68 $self->{maxAutoSiblings} = 256 if not defined $self->{maxAutoSiblings};
69  
70 $self->init();
71  
72 return $self;
73 }
74  
75  
76 ### CLOSE
77 #
78 sub close {
79 my $self = shift;
80 undef $self->{tree};
81 undef $self->{node};
82 undef $self->{doc};
83 }
84  
85  
86 ### INIT
87 #
88 sub init {
89 my $self = shift;
90 unless ($self->{doc}) {
91 if (ref($self->{node})) {
92 $self->{doc} = $self->{node}->ownerDocument;
93 } else {
94 $self->{doc} = XML::LibXML::Document->createDocument( $self->{version}, $self->{encoding} );
95 $self->{doc}->setDocumentElement( $self->{doc}->createElement('root') );
96 }
97 }
98 $self->{node} ||= $self->{doc};
99 $self->{tree} = {};
100 }
101  
102  
103 ### RESET
104 #
105 sub setContextNode {
106 my ($self,$node) = @_;
107 undef $self->{tree};
108 unless (ref($node)) {
109 if ($self->{XPathContext}) {
110 $node=$self->{XPathContext}->find($node)->get_node(1);
111 } else {
112 $node=$self->{node}->find($node)->get_node(1);
113 }
114 }
115 if ($node) {
116 $self->{node} = $node;
117 $self->{doc} = $node->ownerDocument;
118 } else {
119 die "[$PACKAGE] Context node doesn't exist.\n";
120 }
121 }
122  
123  
124 ### RESET
125 #
126 sub reset {
127 my ($self,%args) = @_;
128 $self->close;
129 $self->init(%args);
130 }
131  
132  
133 ### GET IT
134 #
135 sub contextNode { shift->{node} }
136  
137 sub document { shift->{doc} }
138  
139 sub documentElement { shift->{doc}->documentElement }
140
141  
142 ### PARSE
143 #
144 sub parse {
145 my ($self, $data, $value) = @_;
146
147 if (ref($data) eq 'HASH') {
148 foreach my $xpath (sort keys %{$data}) {
149 print "$xpath\n" if $self->{debug};
150 $self->createNode( $xpath, $data->{$xpath} );
151 }
152 } elsif (ref($data) eq 'ARRAY') {
153 # preserve order
154 die "[$PACKAGE] Array must have even number of elements.\n" if (@$data % 2);
155 for (my $i=0; $i<@$data; $i+=2) {
156 print "$data->[$i]\n" if $self->{debug};
157 $self->createNode( $data->[$i], $data->[$i+1] );
158 }
159 } else {
160 $self->createNode( $data, $value );
161 }
162
163 return $self->{doc}->documentElement();
164 }
165  
166  
167 ### _CREATE NODE
168 #
169 # Creates nodes, text nodes and attributes from an xpath and a value.
170 #
171 # Returns the node created
172 #
173  
174 sub createNode {
175 my ($self, $xpath, $value, $context_node) = @_;
176  
177 # strip the uninteresting part
178 $xpath=~s{^\.\s+/}{};
179  
180 # roughly verify that we have an XPath in a supported form:
181 die "[$PACKAGE] Can't create nodes based on XPath $xpath\n" unless $xpath =~ m{^(?:\$${NAME}${FILTER}*)?$STEP*$LAST_STEP$};
182 # return;
183  
184 if ($xpath=~s{^/}{}) {
185 # start from the document level
186 $self->_createSteps($self->{doc},$xpath,$value);
187 } else {
188 if ($xpath =~ s{^(\$${NAME}${FILTER}*)/}{./}) {
189 $context_node = $1;
190 }
191 # start from the current node
192 if ($context_node ne "" and !ref($context_node)) {
193 if ($self->{XPathContext}) {
194 $context_node=$self->{XPathContext}->find($context_node)->get_node(1);
195 } else {
196 $context_node=$self->{node}->find($context_node)->get_node(1);
197 }
198 die "[$PACKAGE] Context node doesn't exist.\n" unless ($context_node);
199 } else {
200 $context_node ||= $self->{node};
201 }
202 $self->_createSteps($context_node,$xpath,$value);
203 }
204 }
205  
206 sub _lookup_namespace {
207 my ($self,$node,$name)=@_;
208 if ($name=~s/^(${NAMECHAR}+)://) {
209 my $prefix = $1;
210 my $uri = $node->lookupNamespaceURI($prefix);
211 if (!defined($uri) and $self->{XPathContext} and
212 UNIVERSAL::can($self->{XPathContext},'lookupNs')) {
213 $uri = $self->{XPathContext}->lookupNs($prefix)
214 }
215 if (!defined($uri) and ref($self->{namespaces})) {
216 $uri = $self->{namespaces}->{ $prefix };
217 }
218 if (!defined($uri)) {
219 warn "Couldn't find namespace URI for the element ${prefix}:${node}!\n";
220 return ($prefix.':'.$name,undef);
221 } else {
222 # find the best suitable prefix
223 my $real_prefix = $node->lookupNamespacePrefix( $uri );
224 if ($real_prefix eq "" and !defined($node->lookupNamespaceURI( undef ))) {
225 $real_prefix = $prefix;
226 }
227 return (($real_prefix ne "") ? $real_prefix.':'.$name : $name , $uri);
228 }
229 } else {
230 return ($name,undef);
231 }
232 }
233  
234 sub _insertNode {
235 my ( $self, $axis, $node, $next ) = @_;
236 if ($axis =~ /^$|^child::|^descendant(?:-or-self)?::/) {
237 $node->appendChild( $next );
238 } elsif ($axis =~ /^(following(?:-sibling)?)::/) {
239 my $parent = $node->parentNode;
240 die "Can't create axis $1 on a document node" unless $parent;
241 $parent->insertAfter( $next, $node );
242 } elsif ($axis =~ /^(preceding(?:-sibling)?)::/) {
243 my $parent = $node->parentNode;
244 die "Can't create axis $1 on a document node" unless $parent;
245 $parent->insertBefore( $next, $node );
246 } elsif ($axis =~ /^(parent|ancestor|ancestor-or-self|self|namespace)::/) {
247 die "Can't create axis $1";
248 }
249 }
250  
251 sub _createSteps {
252 my ($self,$node,$xpath,$value)=@_;
253  
254 while ($xpath ne "") {
255 # get the first step
256 my $step = $xpath;
257 my $rest;
258 if ($step =~ s{^(.*?)\/(.*)$}{$1}) {
259 $rest = $2;
260 }
261  
262 print "$xpath : Processing step: $step (remains $rest)\n" if $self->{debug};
263  
264 my $next = $self->{XPathContext} ?
265 $self->{XPathContext}->find($step,$node)->get_node(1) :
266 $node->find($step)->get_node(1);
267  
268 unless ($next) {
269 # auto-create the node(s) implied by the step
270  
271 if ($step =~ /^(?:@|attribute::)($NAME)/) {
272 my $name = $1;
273 if ($rest eq "") {
274 print "$xpath : auto-creating attribute $name for $step\n" if $self->{debug};
275 my ($real_name,$uri) = $self->_lookup_namespace($node,$name);
276 if (defined($uri) and $uri ne "") {
277 $node->setAttributeNS($uri,$name,$value);
278 return $node->getAttributeNodeNS($uri,$name);
279 } else {
280 $node->setAttribute($name,$value);
281 return $node->getAttributeNode($name);
282 }
283 } else {
284 die "[$PACKAGE] XPath steps follow after an attribute: $step/$rest\n";
285 }
286 } elsif ($step =~ /^($AXIS)text\(\)/) {
287 my $axis = $1;
288 if ($rest eq "") {
289 print "$xpath : auto-creating text() for $step\n" if $self->{debug};
290 $next = $self->{doc}->createTextNode($value);
291 $self->_insertNode( $axis, $node, $next );
292 return $next;
293 } else {
294 die "[$PACKAGE] XPath steps follow after a text(): $step/$rest\n";
295 }
296 } elsif ($step =~ /^($AXIS)comment\(\)/) {
297 my $axis = $1;
298 if ($rest eq "") {
299 print "$xpath : auto-creating comment <!-- $value --> for $step\n" if $self->{debug};
300 $next = $self->{doc}->createComment($value);
301 $self->_insertNode( $axis, $node, $next );
302 return $next;
303 } else {
304 die "[$PACKAGE] XPath steps follow after a text(): $step/$rest\n";
305 }
306 } elsif ($step =~ /^($AXIS)processing-instruction\((${PREDICATE})\)/o) {
307 my $axis = $1;
308 my $name = $2;
309 if ($name=~/^(?:\s*'([^']*)'|"([^"]*)"\s*)$/) {
310 $name=$1.$2;
311 if ($rest eq "") {
312 print "$xpath : auto-creating comment <!-- $value --> for $step\n" if $self->{debug};
313 $next = $self->{doc}->createProcessingInstruction($name,$value);
314 $self->_insertNode( $axis, $node, $next );
315 return $next;
316 } else {
317 die "[$PACKAGE] XPath steps follow after a processing-instruction(): $step/$rest\n";
318 }
319 } else {
320 die "[$PACKAGE] Can't auto-create PI as specified ($name), use processing-instruction('name')\n";
321 }
322 } else {
323 my ($name,$axis);
324 if ($step =~ /^($AXIS)($NAME)(?!\()/) {
325 $axis = $1;
326 $name = $2;
327 };
328 if ($name eq "") {
329 die "[$PACKAGE] Can't determine element name from step $step\n";
330 }
331 my @auto;
332 do {{
333 print "$xpath : auto-creating element $name for $step\n" if $self->{debug};
334 if ($self->{maxAutoSiblings} && @auto>$self->{maxAutoSiblings}) {
335 # unlink all added siblings
336 # print STDERR $self->{doc}->toString(1),"\n @auto\n";
337 $_->unlinkNode for @auto;
338 die "[$PACKAGE] Max automatic creation of siblings overflow ($self->{maxAutoSiblings}) for '$xpath', step '$step'!\n";
339 }
340 my ($real_name,$uri) = $self->_lookup_namespace($node,$name);
341 if (defined($uri) and $uri ne "") {
342 $next = $self->{doc}->createElementNS($uri,$real_name);
343 } else {
344 $next = $self->{doc}->createElement($real_name);
345 }
346 if ($node == $self->{doc}) {
347 $node->setDocumentElement( $next );
348 # iterating won't help here
349 last;
350 } else {
351 $self->_insertNode( $axis, $node, $next );
352 }
353 push @auto,$next;
354  
355 $next = $self->{XPathContext} ?
356 $self->{XPathContext}->find($step,$node)->get_node(1) :
357 $node->find($step)->get_node(1);
358 }} while (!$next);
359 }
360 }
361 $xpath = $rest;
362 $node = $next;
363 };
364  
365 if ($node) {
366 print "Setting value for $xpath\n" if $self->{debug};
367 if ($node->nodeType == XML::LibXML::XML_ATTRIBUTE_NODE()) {
368 $node->setValue($value);
369 } elsif ($node->nodeType != XML::LibXML::XML_ELEMENT_NODE()) {
370 $node->setData($value);
371 } else {
372 $node->removeChildNodes() if $node->hasChildNodes;
373 if (ref($value) and UNIVERSAL::isa($value,'XML::LibXML::Node')) {
374 $node->appendChild( $value );
375 } else {
376 $node->appendTextNode($value) if $value ne "";
377 }
378 }
379 } else {
380 warn "No node for XPath ($xpath)\n";
381 }
382 return $node;
383 }
384  
385 ###
386 #
387 # The following method use a hash to store all the xpaths and their nodes.
388 # Locating a node is purely based on looking up its xpath the way it's been
389 # written. Thus 'somenode[1]' and 'somenode[position()=1]' will be treated as
390 # two different nodes!
391 #
392 # Using proper xpath doc->find to retrieve nodes instead of the hash will
393 # eliminate this problem.
394 #
395 # Anyway:
396 # - if you have a 'node[1]' and a 'node[3]' a 2nd node will not be
397 # created inbetween.
398 # - if you have a 'node[position()=1]' and a 'node[2]' the nodes will
399 # be reversed in the doc (all xpaths are created in alphabetical order).
400 #
401 # ALL OF THESE PROBLEMS HAVE BEEN FIXED IN THE createNode METHOD ABOVE!
402 #
403 #
404 sub _createNode_simple {
405 my ($self, $xpath, $value) = @_;
406  
407 my $name = $xpath;
408 $name =~ s{^.*\/(.*)$}{$1};
409 $name =~ s{\[.*\]$}{};
410
411 my $parent = $xpath;
412 $parent =~ s{^(.*)\/.*$}{$1};
413  
414 if ($parent && !defined $self->{tree}->{$parent}) {
415 $self->_createNode_simple($parent, undef);
416 }
417
418 # Attribute
419 if ($name =~ /^@/) {
420 print " addAttribute: $xpath\n" if $self->{debug};
421 $self->{tree}->{$parent}->setAttribute($name,$value);
422 }
423 # Element
424 else {
425 print " createElement: $xpath\n" if $self->{debug};
426  
427 $self->{tree}->{$xpath} = $self->{doc}->createElement($name);
428
429 if ($parent) {
430 $self->{tree}->{$parent}->appendChild( $self->{tree}->{$xpath} );
431 } else {
432 $self->{doc}->setDocumentElement( $self->{tree}->{$xpath} );
433 }
434
435 $self->{tree}->{$xpath}->appendTextNode($value) if $value;
436 }
437  
438 return undef;
439 }
440  
441  
442 ###########
443 1;
444  
445  
446 __END__