Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

XML::Simple find and add

by hakana (Acolyte)
on Dec 05, 2007 at 09:25 UTC ( [id://655055]=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://655055]
Approved by GrandFather
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (2)
As of 2024-04-19 18:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found