keegita gina
keegita gina

Reputation: 35

Perl XML::Smart : How to update a node value in an xml file?

I am trying to update an xml file from a Perl script using XML::Smart library.

Example XML file:

<food>
    <fruit>
        <name>banana</name>
        <price>12</price>
    </fruit>
    <fruit>
        <name>apple</name>
        <price>13</price>
    </fruit>
    <fruit>
        <name>orange</name>
        <price>19</price>
    </fruit>
</food>

I want to update apple price from 13 to 14 for example.

I tried this:

#!/usr/bin/perl
use XML::Smart;

my $XML = XML::Smart->new(file.xml);

$XML->{food}{fruit}[$X]{price} = 14 ;

$XML->save($file);

This could work if I knew the index number $X of the fruit element named apple. Here we can see it's 1 because indexes start from 0, but in case of multiple fruit elements, how could I get that index knowing only the fruit name?

Upvotes: 0

Views: 389

Answers (1)

Borodin
Borodin

Reputation: 126762

You will have to search the data structure for fruits with a name fiels of apple

You will probably also want to ensure that there is exactly one such element

The code would look like this

use strict;
use warnings 'all';

use XML::Smart;

my $xml = XML::Smart->new(\*DATA);

my $fruits = $xml->{food}{fruit};

my @apples = grep { $_->{name} eq 'apple' } @$fruits;

die scalar @apples . " apples found" unless @apples == 1;

$apples[0]{price} = 14;

print scalar $xml->data(nometagen => 1);



__DATA__
<food>
    <fruit>
        <name>banana</name>
        <price>12</price>
    </fruit>
    <fruit>
        <name>apple</name>
        <price>13</price>
    </fruit>
    <fruit>
        <name>orange</name>
        <price>19</price>
    </fruit>
</food>

output

<?xml version="1.0" encoding="UTF-8" ?>
<food>
  <fruit>
    <name>banana</name>
    <price>12</price>
  </fruit>
  <fruit>
    <name>apple</name>
    <price>14</price>
  </fruit>
  <fruit>
    <name>orange</name>
    <price>19</price>
  </fruit>
</food>

Upvotes: 3

Related Questions