DJpumps has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

When feeding XML::Twig with an XML document that defines a default namespace, then all elements that have no prefix get the #default prefix. This is probably due to XML::Parser::Expat

I assumed that using map_xmlns in the XML::Twig constructor will assign my prefix for the default namespace URL but it doesn't.

Here's an example for the XML Document:

<schema xmlns="http://www.w3.org/2001/XMLSchema"> <element name="alert"/> </schema>

Also, my XML::Twig constructor looks like this:

my $twig = XML::Twig->new( map_xmlns => { xsd => 'http://www.w3.org/2001/XMLSchema', }, );

The problem: when I print $twig->root->gi I get #default:schema while I expect to get xsd:schema.

How can I get XML::Twig to do what I expect it to do (show me the prefix that I assigned to the namespace URL and not show me the #default prefix)?

Thanks.

-- DJpumps

Replies are listed 'Best First'.
Re: XML::Twig and #default prefix
by mirod (Canon) on Dec 12, 2007 at 09:26 UTC

    You got the map_xmlns reversed: it should be map_xmlns => { 'http://www.w3.org/2001/XMLSchema' => 'xsd', }.

    I agree that it is easy to make that mistake though, I'll fix that in the next release, either through a warning, or by swapping the args if it looks like they might be reversed. Thanks.

      Hello,

      I reversed the mapping and I got ns_prefix to report the prefix that I expected, xsd, in this case. That's OK.

      What isn't OK is that namespace returns an empty string and not the namespace URL that I assigned in the mapping. Why?

      Thanks a lot for your rapid response.

      -- DJpumps

        I get the proper result:

        /usr/bin/perl use strict; use warnings; use XML::Twig; my $twig = XML::Twig->parse( map_xmlns => { 'http://www.w3.org/2001/XM +LSchema' => 'xsd', }, \*DATA); printf "\$twig->root->gi: %s\n", $twig->root->gi; printf "\$twig->root->namespace: %s\n", $twig->root->namespace; __DATA__ <schema xmlns="http://www.w3.org/2001/XMLSchema"><element name="alert" +/></schema>

        gives me:

        $twig->root->gi: xsd:schema $twig->root->namespace: http://www.w3.org/2001/XMLSchema

        Which version of XML::Twig are you using? I get the results above with XML::Twig 3.32, the latest CPAN release.