http://qs1969.pair.com?node_id=178692

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

Hello,

Warning XML and Perl newbie. I've created a DOM tree from XML::LibXML::SAX::Builder and the structure is roughly as follows:

<Message> <Body>...Base64_Encoded_Text...</Body> </Message>
I need to replace the Base64 encode text with its decoded value. So far I've been able to decode the contents of the Body with the following:
. . . my $dom = $generator->execute("exec $opt_hash{sp} \'$opt_dates{start}\ +', \'$opt_dates{end}\'"); my $root = $dom->getDocumentElement; my @bodies = $root->getElementsByTagName('Body'); for (my $i = 0; $i < scalar(@bodies); $i++) { print decode_base64($bodies[$i]->getFirstChild->getData); } . . .
However, I'd like to modify the tree directly and not just the list that gets returned from getElementsByName. Can anyone help?

Thanks,
Jay

Replies are listed 'Best First'.
Re: Replace the Text of an XML Element Using LibXML and DOM
by lestrrat (Deacon) on Jul 01, 2002 at 23:09 UTC

    How about:

    foreach my $node ( $dom->findnodes( '/Message/Body' ) ) { my $decoded = decode_base64($node->textContent()); $node->removeChild( $node->firstChild() ); $node->appendTextNode( $decoded ); }
      Thanks so much for the reply,

      Hopefully this can help someone else. I ended up implementing as follows:

      my $root = $dom->getDocumentElement; my $bodies = $root->getElementsByTagName( "MessageBody" ); foreach my $body ( $bodies->get_nodelist() ) { my $encoded_node = $body->firstChild(); $encoded_node->replaceDataString( $encoded_node->data(), decode_ba +se64( $encoded_node->data() )); }
      Again thanks. You got me going on the right path.

      Take care,
      Jay

        I learned something new, too :) ( didn't know about replaceDataString() )