Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Replace the Text of an XML Element Using LibXML and DOM

by jmurphy (Novice)
on Jul 01, 2002 at 21:38 UTC ( #178692=perlquestion: print w/ replies, xml ) Need Help??
jmurphy has asked for the wisdom of the Perl Monks concerning the following question:


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?


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,

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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://178692]
Approved by emilford
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2016-07-02 07:14 GMT
Find Nodes?
    Voting Booth?
    What is your favorite alternate name for a (specific) keyboard key?

    Results (19 votes). Check out past polls.