Unable to update content in xml tag using XML::Twig

48 views Asked by At

I am unable to update content in xml tag using xml Twig module.

Here is my xml file :-

<?xml version="1.0"?>
<test customerProprietary="false">
  <classes>
    <class name="new" />
  </classes>
  <chars>
    <log>false</log>
  </chars>
</test>

Code snippet:-

  my $twig = XML::Twig->new(
     pretty_print => 'indented',
     twig_handlers => {
             log   => sub {
                             if ($_->text eq 'true'){
                               exit;
                             }
                             else{
                               print $_->text;
                               subp4open($xmlfile);
                               $_->set_text( 'true' );
                               exit;
                            }
       }
);

$twig->parsefile($script_path);
$twig->print_to_file($script_path);

i have to update <log>false</log> to <log>true</log>. Am i missing something here?

2

There are 2 answers

0
choroba On BEST ANSWER

That's because exit exits the program, so print_to_file is never reached. Remove the exits. You can replace them with returns, but they aren't needed.

0
brian d foy On

When I run into these sorts of things, I like to put a statement like say "This far" to see that I've made it to a particular part of the code:

say "About to parse file";
$twig->parsefile($script_path);
say "About to print file";
$twig->print_to_file($script_path);

In your handler, there are some things that you can improve. Since you don't want to do anything in the case that the value is already true, don't even think about that case:

       log   => sub {
                         if ($_->text ne 'true'){
                           print $_->text;
                           subp4open($xmlfile);
                           $_->set_text( 'true' );
                        }
                 },

I might be inclined to always update the value if you want them all to be true. I don't care what it was before as long as I get what I want at the end (although this way tweak your source control a bit):

       log   => sub { $_->set_text( 'true' ) },

Also, I might consider doing any Perforce magic outside of the twig handler. Get the lock on the file before you give it to Twig. If you can't get that lock, you might as well not process it. Then, remember to release it later. If you do all of those operations close together, you're less likely to forget a step.