Nimrod Yanai
Nimrod Yanai

Reputation: 819

Change xml field value depending on values from list

I have an XML file with several fields. One of the fields is a reference number (unique). Another field is a profile-id (not unique), which is always the same for all listings.

Separately, I have a list of reference numbers and their profile-ids (in an excel file). What I want to do is automatically match the reference number field, and change the profile-id field in the xml according to the list, so that the resulting xml will have a correct listing of the reference numbers and their respective profile-ids from the list instead of the general, same profile they have now.

Is this possible?

In the example below: the z303-profile-id field is the same for both patrons, each has a unique identifier in z303-ref, and the former is changed according to the latter in the list.

Thank you.

Example:

<patron-record>
    <z303>
      <z303-ref>000018804</z303-ref>
      <z303-profile-id>USE_MSL</z303-profile-id>
    </z303>
</patron-record>
<patron-record>
    <z303>
      <z303-ref>000018867</z303-ref>
      <z303-profile-id>USE_MSL</z303-profile-id>
    </z303>
</patron-record>

List:

000018804               full staff
000018867               Tester

Result:

<patron-record>
    <z303>
      <z303-ref>000018804</z303-ref>
      <z303-profile-id>full staff</z303-profile-id>
    </z303>
</patron-record>
<patron-record>
    <z303>
      <z303-ref>000018867</z303-ref>
      <z303-profile-id>Tester</z303-profile-id>
    </z303>
</patron-record>

Upvotes: 0

Views: 648

Answers (1)

choroba
choroba

Reputation: 241868

Here's how you can do it in xsh, a tool I happen to maintain:

perl {
    open my $LST, '<', shift or die $!;
    while (<$LST>) {
        chomp;
        my ($ref, $id) = split ' ', $_, 2;
        $profile_id->{$ref} = $id;
    }
} ;
open { shift };
for //patron-record/z303 {
    my $new_id = xsh:lookup('profile_id', z303-ref) ;
    if $new_id set z303-profile-id $new_id ;
}
save :b ;

Call as

xsh -al script.xsh file.lst file.xml

Had you specified the list in an XML file, too, the code would have been much simpler.

Upvotes: 2

Related Questions