Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Replace the Text of an XML Element Using LibXML and DOM

by jmurphy (Acolyte)
on Jul 01, 2002 at 21:38 UTC ( [id://178692]=perlquestion: print w/replies, xml ) Need Help??

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() )

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2024-04-26 00:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found