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

Hi Monkees,

Actually, put a hold on this for the moment - setting forcearray to 1 seems to resolve my initial problem, but I may be back with further probs. RSN...

With the following code, I want $xml_src and $xml_out to be identical, but everything inside bar ends up as an attribute of bar. What am I doing wrong?

I'm fairly sure that it's to do with needing keyattr and forcearray, but I'm struggling to understand what I'm meant to do...

use strict; use XML::Simple; my $xml_src = '<foo> <bar><number>1</number><foobar>Hello world</foobar><barfoo>Goodbye w +orld</barfoo></bar> <bar><number>2</number><foobar>abc</foobar><barfoo>def</barfoo></bar +> </foo>' ; my $xml_in = XMLin($xml_src, ); my $xml_out = XMLout(Test(), rootname=>'foo'); # how do I make $xml_out == $xml_src ? print "Source:\n" . $xml_src . "\n\n"; print "Output:\n" . $xml_out . "\n"; sub Test{ my $entry; my $out; foreach $entry(@{${$xml_in}{'bar'}}){ push @{${$out}{'bar'}}, $entry; } return $out; }

Can anyone advise?

Tom Melly, tom@tomandlu.co.uk

Replies are listed 'Best First'.
Re: XML::Simple help please
by broquaint (Abbot) on Apr 30, 2004 at 11:10 UTC
    If you pass ForceArray to XMLin() you should get equivalent XML for both $xml_src and $xml_out e.g
    my $xml_src = '<foo> <bar><number>1</number><foobar>Hello world</foobar><barfoo>Goodbye w +orld</barfoo></bar> <bar><number>2</number><foobar>abc</foobar><barfoo>def</barfoo></bar +> </foo>' ; my $xml_in = XMLin($xml_src, ForceArray => 1); my $xml_out = XMLout(Test(), rootname=>'foo'); print "Source:\n" . $xml_src . "\n\n"; print "Output:\n" . $xml_out . "\n"; sub Test{ my $entry; my $out; foreach $entry(@{${$xml_in}{'bar'}}){ push @{${$out}{'bar'}}, {%$entry} } return $out; } __output__ Source: <foo> <bar><number>1</number><foobar>Hello world</foobar><barfoo>Goodbye w +orld</barfoo></bar> <bar><number>2</number><foobar>abc</foobar><barfoo>def</barfoo></bar +> </foo> Output: <foo> <bar> <number>1</number> <barfoo>Goodbye world</barfoo> <foobar>Hello world</foobar> </bar> <bar> <number>2</number> <barfoo>def</barfoo> <foobar>abc</foobar> </bar> </foo>
    HTH

    _________
    broquaint

      On my system XML::Simple requires ForceArray to be forcearray all lower case. I don't know if thats a 'feature' of my version or if its the intended behaviou. I know the docs show it with capitals so just be warned that doesn't work in some places.

      update: I seem to have version 1.06 which is old. hmm off to update it :)


      ___________
      Eric Hodges
Re: XML::Simple help please
by gellyfish (Monsignor) on Apr 30, 2004 at 11:06 UTC

    YOu need to use the NoAttr option on the XMLout:

    my $xml_out = XMLout(Test(), rootname=>'foo',NoAttr => 1);

    /J\