Reputation: 8895
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.
Upvotes: 1
Views: 178
Reputation: 16171
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.
Upvotes: 4
Reputation: 126762
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;
}
Upvotes: 1