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

Could I get some help regarding finding a specific item in the xmlfile using the id attribute and then add some other attributes to that item.
<exec> <tc id="001.001" version=""> </tc> </exec>
using KeyAttr => 'tc' to read the xmlfile and tried something like:
foreach my $tc (@{$xml->{tc}}) { if ($tc->{id} eq '001.001') { $xml->{tc}{version => '...'}; }; } }
Is there a better way to find the specific tc (id) of interest? How shall I add the other attributes to that item?

Replies are listed 'Best First'.
Re: XML::Simple find and add
by reasonablekeith (Deacon) on Dec 05, 2007 at 10:59 UTC
    KeyAttr should be 'id', (which is set by default anyway), you also need to set on ForceArray (a single 'tc' element would parse differently otherwise, have a look in the docs.)

    The total code is then as simple as...

    my $xml_string = qq| <exec> <tc id="001.001" version=""/> </exec>|; my $xml_simple = XMLin( $xml_string, 'ForceArray' => 1); $xml_simple->{'tc'}->{'001.001'}->{'version'} = "new value"; print XMLout($xml_simple);
    ---
    my name's not Keith, and I'm not reasonable.