Search code examples
xmlperlxml-twig

XML Twig always editing the XML


I'm sure I'm not using it correctly, my code:

#!/usr/bin/env perl
use strict;
use warnings;
use XML::Twig;

XML::Twig->new( pretty_print  => 'indented',
                twig_handlers => { '//Item[@PartNumber]' => \&_pitem
                                  },
)->parsefile_inplace( 'order2.xml', '.bak' );

sub _pitem {
    $_->set_text(...) if (....);
}

If there are no elements matching that XPath expression in the XML, seems like the XML turns out to be empty...it truncates the file. my desired behavior is: avoid editing the XML at all, if no elements are matched.


Solution

  • If you use parsefile_inplace then the file will be overwritten in any case.

    You need either to flush the file, or manage the creation of a new file yourself if necessary.

    You can use the code from XML::Twig as a basis.