简体   繁体   English

Perl XML :: Smart:如何更新xml文件中的节点值?

[英]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. 我正在尝试使用XML :: Smart库从Perl脚本更新xml文件。

Example XML file: 示例XML文件:

<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. 例如,我想将苹果价格从13更新为14。

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. 如果我知道名为apple的水果元素的索引号$ X,则可以这样做。 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? 在这里我们可以看到它是1,因为索引从0开始,但是在有多个水果元素的情况下,我如何只知道水果名称就能得到那个索引?

You will have to search the data structure for fruits with a name fiels of apple 您将不得不在数据结构中搜索name apples的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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM