3 # XML::NamespaceSupport - a simple generic namespace processor
4 # Robin Berjon <robin@knowscape.com>
7 package XML::NamespaceSupport;
9 use constant FATALS => 0; # root object
10 use constant NSMAP => 1;
11 use constant UNKNOWN_PREF => 2;
12 use constant AUTO_PREFIX => 3;
13 use constant XMLNS_11 => 4;
14 use constant DEFAULT => 0; # maps
15 use constant PREFIX_MAP => 1;
16 use constant DECLARATIONS => 2;
18 use vars qw($VERSION $NS_XMLNS $NS_XML);
20 $NS_XMLNS = 'http://www.w3.org/2000/xmlns/';
21 $NS_XML = 'http://www.w3.org/XML/1998/namespace';
24 # add the ns stuff that baud wants based on Java's xml-writer
27 #-------------------------------------------------------------------#
29 #-------------------------------------------------------------------#
31 my $class = ref($_[0]) ? ref(shift) : shift;
37 { xml => $NS_XML }, # PREFIX_MAP
44 $self->[NSMAP]->[0]->[PREFIX_MAP]->{xmlns} = $NS_XMLNS if $options->{xmlns};
45 $self->[FATALS] = $options->{fatal_errors} if defined $options->{fatal_errors};
46 $self->[AUTO_PREFIX] = $options->{auto_prefix} if defined $options->{auto_prefix};
47 $self->[XMLNS_11] = $options->{xmlns_11} if defined $options->{xmlns_11};
48 return bless $self, $class;
50 #-------------------------------------------------------------------#
52 #-------------------------------------------------------------------#
53 # reset() - return to the original state (for reuse)
54 #-------------------------------------------------------------------#
57 $#{$self->[NSMAP]} = 0;
59 #-------------------------------------------------------------------#
61 #-------------------------------------------------------------------#
62 # push_context() - add a new empty context to the stack
63 #-------------------------------------------------------------------#
66 push @{$self->[NSMAP]}, [
67 $self->[NSMAP]->[-1]->[DEFAULT],
68 { %{$self->[NSMAP]->[-1]->[PREFIX_MAP]} },
72 #-------------------------------------------------------------------#
74 #-------------------------------------------------------------------#
75 # pop_context() - remove the topmost context fromt the stack
76 #-------------------------------------------------------------------#
79 die 'Trying to pop context without push context' unless @{$self->[NSMAP]} > 1;
80 pop @{$self->[NSMAP]};
82 #-------------------------------------------------------------------#
84 #-------------------------------------------------------------------#
85 # declare_prefix() - declare a prefix in the current scope
86 #-------------------------------------------------------------------#
92 warn <<' EOWARN' unless defined $prefix or $self->[AUTO_PREFIX];
94 If you wish to set the default namespace, use the empty string ''.
95 If you wish to autogenerate prefixes, set the auto_prefix option
99 no warnings 'uninitialized';
100 if ($prefix eq 'xml' and $value ne $NS_XML) {
101 die "The xml prefix can only be bound to the $NS_XML namespace."
103 elsif ($value eq $NS_XML and $prefix ne 'xml') {
104 die "the $NS_XML namespace can only be bound to the xml prefix.";
106 elsif ($value eq $NS_XML and $prefix eq 'xml') {
109 return 0 if index(lc($prefix), 'xml') == 0;
110 use warnings 'uninitialized';
112 if (defined $prefix and $prefix eq '') {
113 $self->[NSMAP]->[-1]->[DEFAULT] = $value;
116 die "Cannot undeclare prefix $prefix" if $value eq '' and not $self->[XMLNS_11];
117 if (not defined $prefix and $self->[AUTO_PREFIX]) {
119 $prefix = $self->[UNKNOWN_PREF]++;
120 last if not exists $self->[NSMAP]->[-1]->[PREFIX_MAP]->{$prefix};
123 elsif (not defined $prefix and not $self->[AUTO_PREFIX]) {
126 $self->[NSMAP]->[-1]->[PREFIX_MAP]->{$prefix} = $value;
128 push @{$self->[NSMAP]->[-1]->[DECLARATIONS]}, $prefix;
131 #-------------------------------------------------------------------#
133 #-------------------------------------------------------------------#
134 # declare_prefixes() - declare several prefixes in the current scope
135 #-------------------------------------------------------------------#
136 sub declare_prefixes {
139 while (my ($k,$v) = each %prefixes) {
140 $self->declare_prefix($k,$v);
143 #-------------------------------------------------------------------#
145 #-------------------------------------------------------------------#
147 #-------------------------------------------------------------------#
148 sub undeclare_prefix {
151 return unless not defined $prefix or $prefix eq '';
152 return unless exists $self->[NSMAP]->[-1]->[PREFIX_MAP]->{$prefix};
154 my ( $tfix ) = grep { $_ eq $prefix } @{$self->[NSMAP]->[-1]->[DECLARATIONS]};
155 if ( not defined $tfix ) {
156 die "prefix $prefix not declared in this context\n";
159 @{$self->[NSMAP]->[-1]->[DECLARATIONS]} = grep { $_ ne $prefix } @{$self->[NSMAP]->[-1]->[DECLARATIONS]};
160 delete $self->[NSMAP]->[-1]->[PREFIX_MAP]->{$prefix};
162 #-------------------------------------------------------------------#
164 #-------------------------------------------------------------------#
165 # get_prefix() - get a (random) prefix for a given URI
166 #-------------------------------------------------------------------#
171 # we have to iterate over the whole hash here because if we don't
172 # the iterator isn't reset and the next pass will fail
174 while (my ($k, $v) = each %{$self->[NSMAP]->[-1]->[PREFIX_MAP]}) {
175 $pref = $k if $v eq $uri;
179 #-------------------------------------------------------------------#
181 #-------------------------------------------------------------------#
182 # get_prefixes() - get all the prefixes for a given URI
183 #-------------------------------------------------------------------#
188 return keys %{$self->[NSMAP]->[-1]->[PREFIX_MAP]} unless defined $uri;
189 return grep { $self->[NSMAP]->[-1]->[PREFIX_MAP]->{$_} eq $uri } keys %{$self->[NSMAP]->[-1]->[PREFIX_MAP]};
191 #-------------------------------------------------------------------#
193 #-------------------------------------------------------------------#
194 # get_declared_prefixes() - get all prefixes declared in the last context
195 #-------------------------------------------------------------------#
196 sub get_declared_prefixes {
197 return @{$_[0]->[NSMAP]->[-1]->[DECLARATIONS]};
199 #-------------------------------------------------------------------#
201 #-------------------------------------------------------------------#
202 # get_uri() - get an URI given a prefix
203 #-------------------------------------------------------------------#
208 warn "Prefix must not be undef in get_uri(). The emtpy prefix must be ''" unless defined $prefix;
210 return $self->[NSMAP]->[-1]->[DEFAULT] if $prefix eq '';
211 return $self->[NSMAP]->[-1]->[PREFIX_MAP]->{$prefix} if exists $self->[NSMAP]->[-1]->[PREFIX_MAP]->{$prefix};
214 #-------------------------------------------------------------------#
216 #-------------------------------------------------------------------#
217 # process_name() - provide details on a name
218 #-------------------------------------------------------------------#
224 if ($self->[FATALS]) {
225 return( ($self->_get_ns_details($qname, $aflag))[0,2], $qname );
228 eval { return( ($self->_get_ns_details($qname, $aflag))[0,2], $qname ); }
231 #-------------------------------------------------------------------#
233 #-------------------------------------------------------------------#
234 # process_element_name() - provide details on a element's name
235 #-------------------------------------------------------------------#
236 sub process_element_name {
240 if ($self->[FATALS]) {
241 return $self->_get_ns_details($qname, 0);
244 eval { return $self->_get_ns_details($qname, 0); }
247 #-------------------------------------------------------------------#
250 #-------------------------------------------------------------------#
251 # process_attribute_name() - provide details on a attribute's name
252 #-------------------------------------------------------------------#
253 sub process_attribute_name {
257 if ($self->[FATALS]) {
258 return $self->_get_ns_details($qname, 1);
261 eval { return $self->_get_ns_details($qname, 1); }
264 #-------------------------------------------------------------------#
267 #-------------------------------------------------------------------#
268 # ($ns, $prefix, $lname) = $self->_get_ns_details($qname, $f_attr)
269 # returns ns, prefix, and lname for a given attribute name
270 # >> the $f_attr flag, if set to one, will work for an attribute
271 #-------------------------------------------------------------------#
272 sub _get_ns_details {
277 my ($ns, $prefix, $lname);
278 (my ($tmp_prefix, $tmp_lname) = split /:/, $qname, 3)
279 < 3 or die "Invalid QName: $qname";
282 my $cur_map = $self->[NSMAP]->[-1];
283 if (not defined($tmp_lname)) {
286 # attr don't have a default namespace
287 $ns = ($aflag) ? undef : $cur_map->[DEFAULT];
292 if (exists $cur_map->[PREFIX_MAP]->{$tmp_prefix}) {
293 $prefix = $tmp_prefix;
295 $ns = $cur_map->[PREFIX_MAP]->{$prefix}
297 else { # no ns -> lname == name, all rest undef
298 die "Undeclared prefix: $tmp_prefix";
302 return ($ns, $prefix, $lname);
304 #-------------------------------------------------------------------#
306 #-------------------------------------------------------------------#
307 # parse_jclark_notation() - parse the Clarkian notation
308 #-------------------------------------------------------------------#
309 sub parse_jclark_notation {
312 $jc =~ m/^\{(.*)\}([^}]+)$/;
315 #-------------------------------------------------------------------#
318 #-------------------------------------------------------------------#
320 #-------------------------------------------------------------------#
321 *XML::NamespaceSupport::pushContext = \&push_context;
322 *XML::NamespaceSupport::popContext = \&pop_context;
323 *XML::NamespaceSupport::declarePrefix = \&declare_prefix;
324 *XML::NamespaceSupport::declarePrefixes = \&declare_prefixes;
325 *XML::NamespaceSupport::getPrefix = \&get_prefix;
326 *XML::NamespaceSupport::getPrefixes = \&get_prefixes;
327 *XML::NamespaceSupport::getDeclaredPrefixes = \&get_declared_prefixes;
328 *XML::NamespaceSupport::getURI = \&get_uri;
329 *XML::NamespaceSupport::processName = \&process_name;
330 *XML::NamespaceSupport::processElementName = \&process_element_name;
331 *XML::NamespaceSupport::processAttributeName = \&process_attribute_name;
332 *XML::NamespaceSupport::parseJClarkNotation = \&parse_jclark_notation;
333 *XML::NamespaceSupport::undeclarePrefix = \&undeclare_prefix;
334 #-------------------------------------------------------------------#
338 #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,#
339 #`,`, Documentation `,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,#
340 #```````````````````````````````````````````````````````````````````#
346 XML::NamespaceSupport - a simple generic namespace support class
350 use XML::NamespaceSupport;
351 my $nsup = XML::NamespaceSupport->new;
353 # add a new empty context
355 # declare a few prefixes
356 $nsup->declare_prefix($prefix1, $uri1);
357 $nsup->declare_prefix($prefix2, $uri2);
359 $nsup->declare_prefixes($prefix1 => $uri1, $prefix2 => $uri2);
361 # get a single prefix for a URI (randomly)
362 $prefix = $nsup->get_prefix($uri);
363 # get all prefixes for a URI (probably better)
364 @prefixes = $nsup->get_prefixes($uri);
365 # get all prefixes in scope
366 @prefixes = $nsup->get_prefixes();
367 # get all prefixes that were declared for the current scope
368 @prefixes = $nsup->get_declared_prefixes;
369 # get a URI for a given prefix
370 $uri = $nsup->get_uri($prefix);
372 # get info on a qname (java-ish way, it's a bit weird)
373 ($ns_uri, $local_name, $qname) = $nsup->process_name($qname, $is_attr);
374 # the same, more perlish
375 ($ns_uri, $prefix, $local_name) = $nsup->process_element_name($qname);
376 ($ns_uri, $prefix, $local_name) = $nsup->process_attribute_name($qname);
378 # remove the current context
381 # reset the object for reuse in another document
384 # a simple helper to process Clarkian Notation
385 my ($ns, $lname) = $nsup->parse_jclark_notation('{http://foo}bar');
386 # or (given that it doesn't care about the object
387 my ($ns, $lname) = XML::NamespaceSupport->parse_jclark_notation('{http://foo}bar');
392 This module offers a simple to process namespaced XML names (unames)
393 from within any application that may need them. It also helps maintain
394 a prefix to namespace URI map, and provides a number of basic checks.
396 The model for this module is SAX2's NamespaceSupport class, readable at
397 http://www.megginson.com/SAX/Java/javadoc/org/xml/sax/helpers/NamespaceSupport.html.
398 It adds a few perlisations where we thought it appropriate.
404 =item * XML::NamespaceSupport->new(\%options)
406 A simple constructor.
408 The options are C<xmlns>, C<fatal_errors>, and C<auto_prefix>
410 If C<xmlns> is turned on (it is off by default) the mapping from the
411 xmlns prefix to the URI defined for it in DOM level 2 is added to the
412 list of predefined mappings (which normally only contains the xml
415 If C<fatal_errors> is turned off (it is on by default) a number of
416 validity errors will simply be flagged as failures, instead of
419 If C<auto_prefix> is turned on (it is off by default) when one
420 provides a prefix of C<undef> to C<declare_prefix> it will generate a
421 random prefix mapped to that namespace. Otherwise an undef prefix will
422 trigger a warning (you should probably know what you're doing if you
423 turn this option on).
425 If C<xmlns_11> us turned off, it becomes illegal to undeclare namespace
426 prefixes. It is on by default. This behaviour is compliant with Namespaces
427 in XML 1.1, turning it off reverts you to version 1.0.
429 =item * $nsup->push_context
431 Adds a new empty context to the stack. You can then populate it with
432 new prefixes defined at this level.
434 =item * $nsup->pop_context
436 Removes the topmost context in the stack and reverts to the previous
437 one. It will die() if you try to pop more than you have pushed.
439 =item * $nsup->declare_prefix($prefix, $uri)
441 Declares a mapping of $prefix to $uri, at the current level.
443 Note that with C<auto_prefix> turned on, if you declare a prefix
444 mapping in which $prefix is undef(), you will get an automatic prefix
445 selected for you. If it is off you will get a warning.
447 This is useful when you deal with code that hasn't kept prefixes around
448 and need to reserialize the nodes. It also means that if you want to
449 set the default namespace (ie with an empty prefix) you must use the
450 empty string instead of undef. This behaviour is consistent with the
451 SAX 2.0 specification.
453 =item * $nsup->declare_prefixes(%prefixes2uris)
455 Declares a mapping of several prefixes to URIs, at the current level.
457 =item * $nsup->get_prefix($uri)
459 Returns a prefix given an URI. Note that as several prefixes may be
460 mapped to the same URI, it returns an arbitrary one. It'll return
463 =item * $nsup->get_prefixes($uri)
465 Returns an array of prefixes given an URI. It'll return all the
466 prefixes if the uri is undef.
468 =item * $nsup->get_declared_prefixes
470 Returns an array of all the prefixes that have been declared within
471 this context, ie those that were declared on the last element, not
472 those that were declared above and are simply in scope.
474 =item * $nsup->get_uri($prefix)
476 Returns a URI for a given prefix. Returns undef on failure.
478 =item * $nsup->process_name($qname, $is_attr)
480 Given a qualified name and a boolean indicating whether this is an
481 attribute or another type of name (those are differently affected by
482 default namespaces), it returns a namespace URI, local name, qualified
483 name tuple. I know that that is a rather abnormal list to return, but
484 it is so for compatibility with the Java spec. See below for more
485 Perlish alternatives.
487 If the prefix is not declared, or if the name is not valid, it'll
488 either die or return undef depending on the current setting of
491 =item * $nsup->undeclare_prefix($prefix);
493 Removes a namespace prefix from the current context. This function may
494 be used in SAX's end_prefix_mapping when there is fear that a namespace
495 declaration might be available outside their scope (which shouldn't
496 normally happen, but you never know ;). This may be needed in order to
497 properly support Namespace 1.1.
499 =item * $nsup->process_element_name($qname)
501 Given a qualified name, it returns a namespace URI, prefix, and local
502 name tuple. This method applies to element names.
504 If the prefix is not declared, or if the name is not valid, it'll
505 either die or return undef depending on the current setting of
508 =item * $nsup->process_attribute_name($qname)
510 Given a qualified name, it returns a namespace URI, prefix, and local
511 name tuple. This method applies to attribute names.
513 If the prefix is not declared, or if the name is not valid, it'll
514 either die or return undef depending on the current setting of
519 Resets the object so that it can be reused on another document.
523 All methods of the interface have an alias that is the name used in
524 the original Java specification. You can use either name
525 interchangeably. Here is the mapping:
528 ---------------------------------------------------
529 pushContext push_context
530 popContext pop_context
531 declarePrefix declare_prefix
532 declarePrefixes declare_prefixes
534 getPrefixes get_prefixes
535 getDeclaredPrefixes get_declared_prefixes
537 processName process_name
538 processElementName process_element_name
539 processAttributeName process_attribute_name
540 parseJClarkNotation parse_jclark_notation
541 undeclarePrefix undeclare_prefix
545 Two global variables are made available to you. They used to be constants but
546 simple scalars are easier to use in a number of contexts. They are not
547 exported but can easily be accessed from any package, or copied into it.
553 The namespace for xmlns prefixes, http://www.w3.org/2000/xmlns/.
557 The namespace for xml prefixes, http://www.w3.org/XML/1998/namespace.
564 - optimise here and there
568 Robin Berjon, robin@knowscape.com, with lots of it having been done
569 by Duncan Cameron, and a number of suggestions from the perl-xml
574 Copyright (c) 2001-2005 Robin Berjon. All rights reserved. This program is
575 free software; you can redistribute it and/or modify it under the same terms