http://www.perlmonks.org?node_id=970050

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

I read in and parse the below XML fine, it populates a hash with the values I want. In one area I want to increment the nextSessionID from the XML read in and then write the XML document back. When I run the below I get the XML document overwritten with an element with all other named tags being attributes of the main tag. Starting XML
<?xml version="1.0" encoding="UTF-8"?> <mainTag> <items> <nextSessionID>1000</nextSessionID> </items> </mainTag>
After write I get
<?xml version='1.0'?> <items nextSessionID="1001" />
The segment of the program that deals with the XML document being read in and written out.
my $xmlSimp = XML::Simple->new(); my $xmlCont = $xmlSimp->XMLin($xmlPath); my $varIn = ""; our %xmlHash; foreach my $keyI (keys (%{$xmlCont->{"items"}})) { $varIn = $xmlCont->{"items"}->{$keyI}; $xmlHash{$keyI} = $varIn; if ($keyI eq "nextSessionID") { $xmlCont->{"items"}->{$keyI} = ++$varIn; } } my $tmpOut = $xmlSimp->XMLout($xmlCont, KeepRoot => 1, OutputFile => $xmlPath, XMLDecl => "<?xml version='1.0'?>" );

Replies are listed 'Best First'.
Re: Problem saving XML
by Corion (Patriarch) on May 11, 2012 at 16:07 UTC

    You likely want to read up on the SuppressEmpty option, and maybe restructure your data structure so that XML::Simple recognizes that nextSessionID should be a tag, not an attribute. Maybe KeyAttr is the relevant thing to use there.

      Thanks for the info. Any chance you could put an example of what you're referring to? I'm trying some stuff but nothing seems to be working. Also, why would the mainTag go missing altogether? I haven't touched this in a long time and even then I haven't done much with it. Any further help you can give would be much appreciated. Thank-you.