Perl XML::Smart : How to update a node value in an xml file? -
i trying update xml file 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 update apple price 13 14 example.
i tried this:
#!/usr/bin/perl use xml::smart; $xml = xml::smart->new(file.xml); $xml->{food}{fruit}[$x]{price} = 14 ; $xml->save($file);
this work if knew index number $x of fruit element named apple. here can see it's 1 because indexes start 0, in case of multiple fruit elements, how index knowing fruit name?
you have search data structure fruits name
fiels of apple
you want ensure there 1 such element
the code this
use strict; use warnings 'all'; use xml::smart; $xml = xml::smart->new(\*data); $fruits = $xml->{food}{fruit}; @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>
Comments
Post a Comment