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

I have a list of key words that I wish to insert elements for into an existing XML document. What I have so far is:

use strict; use warnings; use XML::Twig; my @keywords = qw(this that the other); my $twig = XML::Twig->new ( pretty_print => 'indented', discard_spaces => 1, keep_encoding => 1, ); $twig->parse (do {local $/; <DATA>}); my $topic = $twig->root (); my @newElts; push @newElts, [keyword => {translate => 'true'}, $_] for @keywords; my $keywordsElt = XML::Twig::Elt->new (keywords => {}, @newElts); $keywordsElt->paste (first_child => $topic); print $twig->sprint (); __DATA__ <?xml version="1.0" encoding="UTF-8"?> <topic> <body> </body> </topic>

which prints:

<?xml version="1.0" encoding="UTF-8"?> <topic> <keywords>ARRAY(0x1fa77a8)ARRAY(0x1fa77e4)ARRAY(0x1fa7850)ARRAY(0x1f +a788c)</keywords> <body></body> </topic>

but what I'd like is:

<?xml version="1.0" encoding="UTF-8"?> <topic> <keywords> <keyword translate='true'>this</keyword> <keyword translate='true'>that</keyword> <keyword translate='true'>the</keyword> <keyword translate='true'>other</keyword> </keywords> <body></body> </topic>

What am I missing?


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re: Inserting new elements in an XML doc using XML::Twig
by ysth (Canon) on Feb 12, 2007 at 06:17 UTC
    I don't know XML::Twig all that well, but the doc says:
    XML::Twig::Elt

    new ($optional_tag, $optional_atts, @optional_content)

    The tag is optional (but then you can't have a content ), the $optional_atts argument is a refreference to a hash of attributes, the content can be just a string or a list of strings and element.

    You are providing a list of arrayrefs where it's expecting strings or elements. Maybe do something like:
    push @newElts, XML::Twig::Elt->new( keyword => {translate => 'true'}, +$_ ) for @keywords;

      Almost right. What I actually was after is:

      push @newElts, XML::Twig::Elt->new( keyword => $_ ) for @keywords;

      mumble, mumble, exactly right actually, mumble,mumble. Err, that is, yes you are exactly right. Thank you. :)

      which generates (when used in the original code):

      <?xml version="1.0" encoding="UTF-8"?> <topic> <keywords> <keyword translate="true">this</keyword> <keyword translate="true">that</keyword> <keyword translate="true">the</keyword> <keyword translate="true">other</keyword> </keywords> <body></body> </topic>

      I read that documentation forwards and backwards several times, looked at the samples following it, and just couldn't see what was wanted. Doh!

      Update: retract silly "almost right" statement. Forgot I needed the attribute!


      DWIM is Perl's answer to Gödel
        I like XML::Twig however the documentation leaves much to be desired. There are to many methods that do the same thing and the function call layout is not easy to follow.