I am trying to add child element to a node in XML using XML:Twig. my XML is
<Install>
<version >
<number>6.0</number>
<build>1037124</build>
<path>path</path>
<kind>kind</kind>
</version>
<version >
<number>7.0</number>
<build>1037124</build>
<path>path</path>
<kind>kind</kind>
</version>
</Install>
and the output I want is:-
<Install>
<version >
<number>6.0</number>
<build>1037124</build>
<path>path/path>
<kind>kind</kind>
<patch>patch</patch>
<patchv>patchv</patchv>
</version>
<version >
<number>7.0</number>
<build>1037124</build>
<path>path</path>
<kind>kind</kind>
</version>
</Install>
I want to add two new child node to parent version where number is 6.0
I have tried this code
my $version = "6.0";
my $file_loc = "data.xml";
my $twig = XML::Twig->new( pretty_print => 'indented_a' )->parsefile( $file_loc );
for my $number ( $twig->findnodes('/Install/version/number') ) {
$number->parent->last_child->insert(
patch => { version =>'patch' },
patchversion => { version =>'patchv' },
) if $number->trimmed_text eq $version;
}
but the output I am getting is not what I want. output is:-
<Install>
<version>
<number>6.0</number>
<build>1037124</build>
<path>path</path>
<kind>
<patch version="patch">
<patchversion version="patchv">kind</patchversion>
</patch>
</kind>
</version>
<version >
<number>7.0</number>
<build>1037124</build>
<path>path</path>
<kind>kind</kind>
</version>
</Install>
I have tried this with other way also using paste as follows:-
my $version = "6.0";
my $file_loc = "data.xml";
my $myXML = <<"XML";
<patch>
<build></build>
<version></version>
</patch>
XML
my $t = XML::Twig->new(
twig_handlers => {
Install => sub { add_version( $myXML, @_ ); }, }
)->parsefile( $file_loc ) or die $!;
$t->set_pretty_print('indented_c');
open my $xml_fh, '>', "$file_loc" or die $!;
$t->print($xml_fh);
sub add_version {
my ( $xml, $t, $install ) = @_;
my $new_elt = XML::Twig::Elt->parse($xml);
for my $number ( $t->findnodes('/Install/version/number') ) {
if($number->trimmed_text eq $version )
{
$new_elt->paste( $number->parent->last_child->paste => $install );
}
}
}
here I am getting following error
cannot paste an element that belongs to a tree at
can I achieve this using insert only or I have to use paste?? How to do it in either case ??
<missing ni your input. While the overall question is very good, please still make sure you post valid code and XML (unless the question is "why does this not compile"). Thanks. :)