Question

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.

Was it helpful?

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.

OTHER TIPS

You have written nothing that outputs any XML.

You should use twig_roots like this

my $twig = XML::Twig->new(
    twig_roots               => { '//Item[@PartNumber]' => \&_pitem },
    twig_print_outside_roots => 1,
    pretty_print             => 'indented',
);

$twig->parsefile_inplace( 'order2.xml', '.bak' );

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

At the end of the _pitem, you have to

$_->flush;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top