3

Let us assume that my XML file is like:

<? xml version="1.0" encoding="iso-8859-1" ?>
  <Body>
    <RequiredTag>
      #VALUE#
    </RequiredTag>
  </Body>

How can I change the value of the required tag using Perl?

E.g.:

$XmlHandle->{XML}->{Body}->{RequiredTag} = "RequiredValue";

1 Answer 1

6

With XML::Twig::

#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

XML::Twig->new( twig_handlers => 
                  { RequiredTag => sub { $_->set_text( 'RequiredValue') } },
                pretty_print => 'indented',
              )
         ->parsefile( 'my_file.xml')
         ->print;
Sign up to request clarification or add additional context in comments.

6 Comments

1. Incase we have more than one "RequiredTag" which is nested under different parent tags. How can we differentiate ? 2. And, how to save the xml file after the modification ?
Have a look at the doc ;--) You can use a more complex expression in the handler trigger, like Body/RequiredTag, or /XML/Body/RequiredTag; and instead of print, you can use print_to_file( 'updated.xml')
print_to_file(FILE) will save the document once i close my Tkx application. Can we save the file dynamically and reload as my Tkx application still running ?
I am not sure what you mean here. print_to_file writes the document to disk as soon as you call the method. If you need the XML for the document, use sprint, which returns the XML string for the entire doc.
I am using GUI application developed in GUI. I pick a button so that it will write the value into the XML file. But the modification will taken into effect if and only if i close the application and re-launch it. With-Out closing the GUI application, the change is not reflected when i try to retrieve the value.. And when i check the documentation, In the doc, "print_to_file ($filename, %options)" %options are not described..
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.