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

I would like to add three different sets of info/data to a existing xml file:
<exec> <tc id=""></tc> </exec>
To produce the following xml file:
<exec> <dut mac="" ip="" model="" firmware=""/> <tc id="" version="" date="" desription/objective=""> <ts id="" desription="" date="" expected_result="" result=""/> </tc> </exec>
The first <dut> will only be added once but there will be severeal instances of <tc> and every <tc> will have one or more <ts> What I got so far is that I have to start read the existing xml file. But wondering how I best insert the data to the xml file? And how often should the xml file be saved?

Replies are listed 'Best First'.
Re: XML::Simple add
by andreas1234567 (Vicar) on Nov 26, 2007 at 09:03 UTC
      Tried the following but it doesn't save to file, how should I do that?
      my $conf = "/home/ember/devices/$Macaddress/$Macaddress.xml"; # create object my $xml = XMLin ($conf, KeepRoot=>1,); # insert element $xml->{dut}{ipaddress} = "$ipaddress"; $xml->{dut}{macaddress} = "$Macaddress"; $xml->{dut}{model} = "$ProdShortName"; $xml->{dut}{frimware} = "$Firmware_Version"; # convert Perl array ref into XML document print XMLout($xml);
Re: XML::Simple add
by strat (Canon) on Nov 27, 2007 at 07:53 UTC

    I would use XML::DOM for it, e.g.

    use XML::DOM; my $file = 'file.xml'; my $xmlParser = XML::DOM::Parser->new; my $xmlDocument = $xmlParser->parsefile( $file ) or die ....; # get parent node my $nodes = $xmlDocument->getElementsByTagName( 'exec' ); my $parentNode = $nodes->item( 0 ) or die "No node with id 0 available\n"; my $newChild = $xmlDocument->createElement('tc'); $newChild->setAttribute( id => '12346' ); $parentNode->appendChild( $newChild ); print $xmlDocument->toString; # debug $xmlDocument->printToFile( $outputfilename) or die ...; $xmlDocument->dispose;

    (Not tested)

    Best regards,
    perl -e "s>>*F>e=>y)\*martinF)stronat)=>print,print v8.8.8.32.11.32"