[XML4Lib] Re: argg, namespaces [resolved]

Eric Lease Morgan emorgan at nd.edu
Sat Jul 14 13:53:31 EDT 2007


On Jul 14, 2007, at 1:39 PM, Eric Lease Morgan wrote:

> Then, using Perl, I create a LibXML parser, parse the file ($input)  
> creating an object, and try to loop through all of the mods elements:
>
>   $parser = XML::LibXML->new;
>   $collection = $parser->parse_file( $input );
>   foreach my $mods ( $collection->findnodes( '//mods' )) {
>
>     my $titles = '';
>     foreach $node ( $mods->findnodes( './/titleInfo/title' )) {
>       $titles .= $node->textContent . '|'
>     }
>
>     # do more cool stuff here
>
>   }


Well, I can resolve my own question, but it seems inelegant.

In short, in order to loop through all the mods elements I need to  
denote a namespace prefix, twice.

   # parse
   my $parser = XML::LibXML->new;
   my $collection = $parser->parse_file( $input );

   # denote a mods namespace
   $collection = XML::LibXML::XPathContext->new( $collection );
   $collection->registerNs( 'mods', 'http://www.loc.gov/mods/v3' );

   # loop through each mods element, note the namespace inclusion
   foreach my $mods ( $collection->findnodes( '//mods:mods' )) {

       # denote the namespace, again!
       $mods = XML::LibXML::XPathContext->new( $mods );
       $mods->registerNs( 'mods', 'http://www.loc.gov/mods/v3' );

       # get the title; note the namespace inclusion
       my $titles = '';
       foreach $node ( $mods->findnodes( './/mods:titleInfo/ 
mods:title' )) {
         $titles .= $node->textContent . '|'
       }

       # do more cool stuff here

   }

The first time I denote/specify the mods namespace I can loop through  
my mods elements. If I do not "re-denote" the mods namespace inside  
the loop, then all of my findnodes methods inside the loop return null.

This just doesn't seem right to me. Argg! Namespaces.

-- 
Eric Morgan




More information about the XML4Lib mailing list