alexlabelle has asked for the wisdom of the Perl Monks concerning the following question:

Looking to make a change to an xml tag from a list of info found in a txt file.

txt file contains a list of data as follows

644111111111,102.23

644255555555,94.8

644492835633,17.71

XML contains two tags where this info can be found:

<KEY_BOL_REF>644111111111</KEY_BOL_REF>

<CARBOL_TRSP_VALUE>0.00</CARBOL_TRSP_VALUE>

I need to find the corresponding 12 digit number from the txt in the xml and replace its CARBOL tag with the amount found next to the number in the text (after the comma). I am able to find the number but can't seem to change the amount of CARBOL. Here is the code i have so far. it also ensures that another tag is set to USD. Thanks.

open(BASE, "C:/POS/POSA.xml"); open(IN, "C:/POS/Macro/awb.txt"); open(OUT, ">POSA_new.xml"); %map = (); while (<IN>) { chomp $_; @items = split(/\,/, $_); $map{$items[0]} = $items[2]; } close IN; $cur_awb = "0"; $cur_val = $map{$items[0]} = $items[2]; while (<BASE>) { chomp $_; if ($_ =~ m/\<KEY_BOL_REF\>(\d*)\<\/KEY_BOL_REF\>/) { $cur_awb = $1; print OUT $_ . "\n"; } elsif ($_ =~ m/\<CARBOL_TRSP_VALUE\>/) { print OUT "\t<CARBOL_TRSP_VALUE>" .$cur_val. "</CARBOL_TRSP_VA +LUE>\n"; } elsif ($_ =~ m/\<CARBOL_TRSP_CUR\/\>/) { print OUT "\t<CARBOL_TRSP_CUR>USD</CARBOL_TRSP_CUR>\n"; } else { print OUT $_ . "\n"; } }
  • Comment on find text in xml tag and replace another tag from data in same txt file
  • Download Code

Replies are listed 'Best First'.
Re: find text in xml tag and replace another tag from data in same txt file
by tangent (Parson) on Jan 28, 2016 at 00:16 UTC
    There are quite a few issues with your script, if you put these two lines at the top you will get an idea:
    use strict; use warnings;
    See The strictures, according to Seuss for why.

    To fix the most obvious try this (untested):

    my %map = (); while (<IN>) { chomp $_; my @items = split(/\,/, $_); $map{$items[0]} = $items[1]; # [1] not [2] } close IN; my ($cur_awb,$cur_val); while (<BASE>) { chomp $_; if ($_ =~ m/\<KEY_BOL_REF\>(\d*)\<\/KEY_BOL_REF\>/) { $cur_awb = $1; $cur_val = $map{$cur_awb}; # should do some error check here print OUT $_ . "\n"; } # ... etc. }
Re: find text in xml tag and replace another tag from data in same txt file
by runrig (Abbot) on Jan 27, 2016 at 23:06 UTC