I am still new with using XML::Twig.
From the main program I look for the elements with attribute @method="create"
In the subroutine player, I want to find the next element/sibling with attribute @method="modify".
Both of these methods fail in subroutine player with the error Can't call method "gi" on an undefined value
my $modif1=$valeur->next_sibling('[@method="modify"]')
my $modif2=$valeur->next_elt('[@method="modify"]')->parent
Example of input.xwo:
<top id="World">
<middle id="France" method="create">
</middle>
<middle id="Germany" method="modify">
</middle>
</top>
My simple code:
#!/bin/perl -w
use warnings;
use XML::Twig;
my $twig= new XML::Twig(
twig_handlers => {
'[@method="create"]' => \&player
}
);
$twig->parsefile("input.xwo");
$twig->purge;
sub player {
my ($twig, $valeur) = @_;
my $modif1 = $valeur->next_sibling('[@method="modify"]');
my $modif2 = $valeur->next_elt('[@method="modify"]')->parent;
print "\nnextELT=" . $modif->gi . "\n";
}
Please always
use strictat the top of your programs and declare variables usingmyat their first point of use. There is no point in bothuse warningsand the-wcommand-line option. The first is preferable.When the twig handler for the
<middle method="create">element is called, the sibling that you require,<middle method="modify">hasn’t been processed. It can’t be found because it isn’t yet in theXML::Twigparse tree.You must either read the entire XML structure and process it afterwards, or write a handler for the element that encloses both the
createandmodifyelements.This program does the latter.
Update
This alternative reads the entire XML tree and extracts the data from it afterwards. It starts by finding all elements in the tree that have a
methodattribute equal to'create', and then finds the following sibling of each of them with amethodattribute of'modify'.