in reply to XML::Simple - Make arrays out of class attribute

XML is a parser. It returns what is. If you want to perform transformations, you'll have to do them yourself.

use Data::Dumper; my $parent = { div => [ { class => 'A', content => '1' }, { class => 'A', content => '2' }, { class => 'A', content => '3' }, { class => 'B', content => '4' }, { class => 'B', content => '5' }, { class => 'B', content => '6' }, ], }; my $grouped = {}; for ( @{ $parent->{div} } ) { my $class = delete $_->{class}; push @{ $grouped->{$class} }, $_; } $parent->{div} = $grouped; print(Dumper($parent));

By the way, the need to perform such transformations could indicate that your XML's schema incorrectly represents your data.

Replies are listed 'Best First'.
Re^2: XML::Simple - Make arrays out of class attribute
by juster (Friar) on Sep 14, 2008 at 22:07 UTC

    OOPS

    After posting this i realized it clobbers the duplicates, which I didnt see at first.

    This is possible with the KeyAttr option:

    #!/usr/bin/perl use Data::Dumper; use XML::Simple; use strict; use warnings; my $filename = shift or die "Usage: decode <filename>\n"; # dies on its own on error my $xmldata = XMLin($filename, KeyAttr => { 'div' => 'class' }); print Dumper $xmldata; __END__
      Your code doesn't work. It deletes 4 of the 6 elements.
Re^2: XML::Simple - Make arrays out of class attribute
by mscharrer (Hermit) on Sep 14, 2008 at 20:10 UTC
    Thanks ikegami for your answer.
    I was trying to avoid doing the transformation by myself. There are already a lot of XML::Simple options which change the structure of the returned hash, i.e. do some form of transformations, so I thought there might be one for this case also. For example if the class would be unique for every div the 'KeyAttr' options would do exactly what I want.

    You are right that the XML code doesn't represent the data correctly. That's because it's XHTML of a webpage where I don't have any influence. It was written for display by a web browser not as a XML database.

    Thanks for your code. I starting to think that I will need it.