File: NamespaceSupport.pm

package info (click to toggle)
libxml-namespacesupport-perl 1.04-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 60 kB
  • ctags: 18
  • sloc: perl: 178; makefile: 33
file content (518 lines) | stat: -rwxr-xr-x 17,924 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

###
# XML::NamespaceSupport - a simple generic namespace processor
# Robin Berjon <robin@knowscape.com>
# 07/10/2001 - v0.03 added Clarkian notation parsing
# 20/09/2001 - v0.02 (w/ lots from Duncan Cameron)
# 16/09/2001 - v0.01
###

package XML::NamespaceSupport;
use strict;

use vars qw($VERSION $NS_XMLNS $NS_XML);
$VERSION    = '1.04';
$NS_XMLNS   = 'http://www.w3.org/2000/xmlns/';
$NS_XML     = 'http://www.w3.org/XML/1998/namespace';


# add the ns stuff that baud wants based on Java's xml-writer


#-------------------------------------------------------------------#
# constructor
#-------------------------------------------------------------------#
sub new {
    my $class   = ref($_[0]) ? ref(shift) : shift;
    my $options = shift;
    my $self = {
                fatals  => 1,
                nsmap   => [{
                              default       => undef,
                              prefix_map    => { xml => $NS_XML },
                              declarations  => undef,
                           }]
               };
    $self->{nsmap}->[0]->{prefix_map}->{xmlns} = $NS_XMLNS if $options->{xmlns};
    $self->{fatals} = $options->{fatal_errors} if defined $options->{fatal_errors};
    $self->{unknown_prefix} = 'aaa';
    return bless $self, $class;
}
#-------------------------------------------------------------------#

#-------------------------------------------------------------------#
# reset() - return to the original state (for reuse)
#-------------------------------------------------------------------#
sub reset {
    my $self = shift;
    $#{$self->{nsmap}} = 0;
}
#-------------------------------------------------------------------#

#-------------------------------------------------------------------#
# push_context() - add a new empty context to the stack
#-------------------------------------------------------------------#
sub push_context {
    my $self = shift;
    push @{$self->{nsmap}}, {
                             default         => $self->{nsmap}->[-1]->{default},
                             prefix_map      => { %{$self->{nsmap}->[-1]->{prefix_map}} },
                             declarations    => [],
                            };
}
#-------------------------------------------------------------------#

#-------------------------------------------------------------------#
# pop_context() - remove the topmost context fromt the stack
#-------------------------------------------------------------------#
sub pop_context {
    my $self = shift;
    die 'Trying to pop context without push context' unless @{$self->{nsmap}} > 1;
    pop @{$self->{nsmap}};
}
#-------------------------------------------------------------------#

#-------------------------------------------------------------------#
# declare_prefix() - declare a prefix in the current scope
#-------------------------------------------------------------------#
sub declare_prefix {
    my $self    = shift;
    my $prefix  = shift;
    my $value   = shift;

    warn "Prefix must not be undef in declare_prefix(). The emtpy prefix must be ''" unless defined $prefix;
    return 0 if $prefix =~ /^xml/i;

    if ($prefix eq '') {
        $self->{nsmap}->[-1]->{default} = $value;
    }
    else {
        die "Cannot undeclare prefix $prefix" if $value eq '';
        if (not defined $prefix) {
            while (1) {
                $prefix = $self->{unknown_prefix}++;
                last if not exists $self->{nsmap}->[-1]->{prefix_map}->{$prefix};
            }
        }
        $self->{nsmap}->[-1]->{prefix_map}->{$prefix} = $value;
    }
    push @{$self->{nsmap}->[-1]->{declarations}}, $prefix;
    return 1;
}
#-------------------------------------------------------------------#

#-------------------------------------------------------------------#
# declare_prefixes() - declare several prefixes in the current scope
#-------------------------------------------------------------------#
sub declare_prefixes {
    my $self     = shift;
    my %prefixes = @_;
    while (my ($k,$v) = each %prefixes) {
        $self->declare_prefix($k,$v);
    }
}
#-------------------------------------------------------------------#

#-------------------------------------------------------------------#
# get_prefix() - get a (random) prefix for a given URI
#-------------------------------------------------------------------#
sub get_prefix {
    my $self    = shift;
    my $uri     = shift;

    # we have to iterate over the whole hash here because if we don't
    # the iterator isn't reset and the next pass will fail
    my $pref;
    while (my ($k, $v) = each %{$self->{nsmap}->[-1]->{prefix_map}}) {
        $pref = $k if $v eq $uri;
    }
    return $pref;
}
#-------------------------------------------------------------------#

#-------------------------------------------------------------------#
# get_prefixes() - get all the prefixes for a given URI
#-------------------------------------------------------------------#
sub get_prefixes {
    my $self    = shift;
    my $uri     = shift;

    return keys %{$self->{nsmap}->[-1]->{prefix_map}} unless defined $uri;
    return grep { $self->{nsmap}->[-1]->{prefix_map}->{$_} eq $uri } keys %{$self->{nsmap}->[-1]->{prefix_map}};
}
#-------------------------------------------------------------------#

#-------------------------------------------------------------------#
# get_declared_prefixes() - get all prefixes declared in the last context
#-------------------------------------------------------------------#
sub get_declared_prefixes {
    my $self = shift;
    return @{$self->{nsmap}->[-1]->{declarations}};
}
#-------------------------------------------------------------------#

#-------------------------------------------------------------------#
# get_uri() - get an URI given a prefix
#-------------------------------------------------------------------#
sub get_uri {
    my $self    = shift;
    my $prefix  = shift;

    warn "Prefix must not be undef in get_uri(). The emtpy prefix must be ''" unless defined $prefix;

    return $self->{nsmap}->[-1]->{default} if $prefix eq '';
    return $self->{nsmap}->[-1]->{prefix_map}->{$prefix} if exists $self->{nsmap}->[-1]->{prefix_map}->{$prefix};
    return undef;
}
#-------------------------------------------------------------------#

#-------------------------------------------------------------------#
# process_name() - provide details on a name
#-------------------------------------------------------------------#
sub process_name {
    my $self    = shift;
    my $qname   = shift;
    my $aflag   = shift;

    my ($ns, $lname);
    eval {
        ($ns, undef, $lname) = $self->_get_ns_details($qname, $aflag);
    };
    if ($@) {
        die $@ if $self->{fatals};
        return undef;
    }
    return ($ns, $lname, $qname);
}
#-------------------------------------------------------------------#

#-------------------------------------------------------------------#
# process_element_name() - provide details on a element's name
#-------------------------------------------------------------------#
sub process_element_name {
    my $self    = shift;
    my $qname   = shift;

    my ($ns, $prefix, $lname);
    eval {
        ($ns, $prefix, $lname) = $self->_get_ns_details($qname, 0);
    };
    if ($@) {
        die $@ if $self->{fatals};
        return undef;
    }
    return ($ns, $prefix, $lname);
}
#-------------------------------------------------------------------#


#-------------------------------------------------------------------#
# process_attribute_name() - provide details on a attribute's name
#-------------------------------------------------------------------#
sub process_attribute_name {
    my $self    = shift;
    my $qname   = shift;

    my ($ns, $prefix, $lname);
    eval {
        ($ns, $prefix, $lname) = $self->_get_ns_details($qname, 1);
    };
    if ($@) {
        die $@ if $self->{fatals};
        return undef;
    }
    return ($ns, $prefix, $lname);
}
#-------------------------------------------------------------------#


#-------------------------------------------------------------------#
# ($ns, $prefix, $lname) = $self->_get_ns_details($qname, $f_attr)
# returns ns, prefix, and lname for a given attribute name
# >> the $f_attr flag, if set to one, will work for an attribute
#-------------------------------------------------------------------#
sub _get_ns_details {
    my $self    = shift;
    my $qname   = shift;
    my $aflag   = shift;

    my ($ns, $prefix, $lname);
    (my ($tmp_prefix, $tmp_lname) = split /:/, $qname, 3)
                                    < 3 or die "Invalid QName: $qname";

    # no prefix
    if (not defined($tmp_lname)) {
        $prefix = undef;
        $lname = $qname;
        # attr don't have a default namespace
        $ns = ($aflag) ? undef : $self->{nsmap}->[-1]->{default};
    }

    # prefix
    else {
        if (exists $self->{nsmap}->[-1]->{prefix_map}->{$tmp_prefix}) {
            $prefix = $tmp_prefix;
            $lname  = $tmp_lname;
            $ns     = $self->{nsmap}->[-1]->{prefix_map}->{$prefix}
        }
        else { # no ns -> lname == name, all rest undef
            die "Undeclared prefix: $tmp_prefix";
        }
    }

    return ($ns, $prefix, $lname);
}
#-------------------------------------------------------------------#

#-------------------------------------------------------------------#
# parse_jclark_notation() - parse the Clarkian notation
#-------------------------------------------------------------------#
sub parse_jclark_notation {
    shift;
    my $jc = shift;
    $jc =~ m/^\{(.*)\}([^}]+)$/;
    return $1, $2;
}
#-------------------------------------------------------------------#


#-------------------------------------------------------------------#
# Java names mapping
#-------------------------------------------------------------------#
*XML::NamespaceSupport::pushContext          = \&push_context;
*XML::NamespaceSupport::popContext           = \&pop_context;
*XML::NamespaceSupport::declarePrefix        = \&declare_prefix;
*XML::NamespaceSupport::declarePrefixes      = \&declare_prefixes;
*XML::NamespaceSupport::getPrefix            = \&get_prefix;
*XML::NamespaceSupport::getPrefixes          = \&get_prefixes;
*XML::NamespaceSupport::getDeclaredPrefixes  = \&get_declared_prefixes;
*XML::NamespaceSupport::getURI               = \&get_uri;
*XML::NamespaceSupport::processName          = \&process_name;
*XML::NamespaceSupport::processElementName   = \&process_element_name;
*XML::NamespaceSupport::processAttributeName = \&process_attribute_name;
*XML::NamespaceSupport::parseJClarkNotation  = \&parse_jclark_notation;
#-------------------------------------------------------------------#


1;
#,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,#
#`,`, Documentation `,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,#
#```````````````````````````````````````````````````````````````````#

=pod

=head1 NAME

XML::NamespaceSupport - a simple generic namespace support class

=head1 SYNOPSIS

  use XML::NamespaceSupport;
  my $nsup = XML::NamespaceSupport->new;

  # add a new empty context
  $nsup->push_context;
  # declare a few prefixes
  $nsup->declare_prefix($prefix1, $uri1);
  $nsup->declare_prefix($prefix2, $uri2);
  # the same shorter
  $nsup->declare_prefixes($prefix1 => $uri1, $prefix2 => $uri2);

  # get a single prefix for a URI (randomly)
  $prefix = $nsup->get_prefix($uri);
  # get all prefixes for a URI (probably better)
  @prefixes = $nsup->get_prefixes($uri);
  # get all prefixes in scope
  @prefixes = $nsup->get_prefixes();
  # get all prefixes that were declared for the current scope
  @prefixes = $nsup->get_declared_prefixes;
  # get a URI for a given prefix
  $uri = $nsup->get_uri($prefix);

  # get info on a qname (java-ish way, it's a bit weird)
  ($ns_uri, $local_name, $qname) = $nsup->process_name($qname, $is_attr);
  # the same, more perlish
  ($ns_uri, $prefix, $local_name) = $nsup->process_element_name($qname);
  ($ns_uri, $prefix, $local_name) = $nsup->process_attribute_name($qname);

  # remove the current context
  $nsup->pop_context;

  # reset the object for reuse in another document
  $nsup->reset;

  # a simple helper to process Clarkian Notation
  my ($ns, $lname) = $nsup->parse_jclark_notation('{http://foo}bar');
  # or (given that it doesn't care about the object
  my ($ns, $lname) = XML::NamespaceSupport->parse_jclark_notation('{http://foo}bar');


=head1 DESCRIPTION

This module offers a simple to process namespaced XML names (unames)
from within any application that may need them. It also helps maintain
a prefix to namespace URI map, and provides a number of basic checks.

The model for this module is SAX2's NamespaceSupport class, readable at
http://www.megginson.com/SAX/Java/javadoc/org/xml/sax/helpers/NamespaceSupport.html.
It adds a few perlisations where we thought it appropriate.

=head1 METHODS

=over 4

=item * XML::NamespaceSupport->new(\%options)

A simple constructor.

The options are C<xmlns> and C<fatal_errors>.

If C<xmlns> is turned on (it is off by default) the mapping from the
xmlns prefix to the URI defined for it in DOM level 2 is added to the
list of predefined mappings (which normally only contains the xml
prefix mapping).

If C<fatal_errors> is turned off (it is on by default) a number of
validity errors will simply be flagged as failures, instead of
die()ing.

=item * $nsup->push_context

Adds a new empty context to the stack. You can then populate it with
new prefixes defined at this level.

=item * $nsup->pop_context

Removes the topmost context in the stack and reverts to the previous
one. It will die() if you try to pop more than you have pushed.

=item * $nsup->declare_prefix($prefix, $uri)

Declares a mapping of $prefix to $uri, at the current level. Note that
if you declare a prefix mapping in which $prefix is undef(), you will
get an automatic prefix selected for you. This is useful when you deal
with code that hasn't kept prefixes around and need to reserialize the
nodes. It also means that if you want to set the default namespace (ie
with an empty prefix) you must use the empty string instead of undef.
This behaviour is consistent with the SAX 2.0 specification.

=item * $nsup->declare_prefixes(%prefixes2uris)

Declares a mapping of several prefixes to URIs, at the current level.

=item * $nsup->get_prefix($uri)

Returns a prefix given an URI. Note that as several prefixes may be
mapped to the same URI, it returns an arbitrary one. It'll return
undef on failure.

=item * $nsup->get_prefixes($uri)

Returns an array of prefixes given an URI. It'll return all the
prefixes if the uri is undef.

=item * $nsup->get_declared_prefixes

Returns an array of all the prefixes that have been declared within
this context, ie those that were declared on the last element, not
those that were declared above and are simply in scope.

=item * $nsup->get_uri($prefix)

Returns a URI for a given prefix. Returns undef on failure.

=item * $nsup->process_name($qname, $is_attr)

Given a qualified name and a boolean indicating whether this is an
attribute or another type of name (those are differently affected by
default namespaces), it returns a namespace URI, local name, qualified
name tuple. I know that that is a rather abnormal list to return, but
it is so for compatibility with the Java spec. See below for more
Perlish alternatives.

If the prefix is not declared, or if the name is not valid, it'll
either die or return undef depending on the current setting of
C<fatal_errors>.

=item * $nsup->process_element_name($qname)

Given a qualified name, it returns a namespace URI, prefix, and local
name tuple. This method applies to element names.

If the prefix is not declared, or if the name is not valid, it'll
either die or return undef depending on the current setting of
C<fatal_errors>.

=item * $nsup->process_attribute_name($qname)

Given a qualified name, it returns a namespace URI, prefix, and local
name tuple. This method applies to attribute names.

If the prefix is not declared, or if the name is not valid, it'll
either die or return undef depending on the current setting of
C<fatal_errors>.

=item * $nsup->reset

Resets the object so that it can be reused on another document.

=back

All methods of the interface have an alias that is the name used in
the original Java specification. You can use either name
interchangeably. Here is the mapping:

  Java name                 Perl name
  ---------------------------------------------------
  pushContext               push_context
  popContext                pop_context
  declarePrefix             declare_prefix
  declarePrefixes           declare_prefixes
  getPrefix                 get_prefix
  getPrefixes               get_prefixes
  getDeclaredPrefixes       get_declared_prefixes
  getURI                    get_uri
  processName               process_name
  processElementName        process_element_name
  processAttributeName      process_attribute_name

=head1 VARIABLES

Two global variables are made available to you. They used to be constants but
simple scalars are easier to use in a number of contexts. They are not
exported but can easily be accessed from any package, or copied into it.

=over 4

=item * C<$NS_XMLNS>

The namespace for xmlns prefixes, http://www.w3.org/2000/xmlns/.

=item * C<$NS_XML>

The namespace for xml prefixes, http://www.w3.org/XML/1998/namespace.

=back

=head1 TODO

 - add more tests
 - optimise here and there

=head1 AUTHOR

Robin Berjon, robin@knowscape.com, with lots of it having been done
by Duncan Cameron, and a number of suggestions from the perl-xml
list.

=head1 COPYRIGHT

Copyright (c) 2001 Robin Berjon. All rights reserved. This program is
free software; you can redistribute it and/or modify it under the same
terms as Perl itself.

=head1 SEE ALSO

XML::Parser::PerlSAX

=cut