http://qs1969.pair.com?node_id=506086

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

I've been puzzling over this too long, and am sure I'm just not looking at it the right way. Hopefully someone with some experience with XML::Twig will have a suggestion.

I'm working on improving some of the datastructures returned by PerlMonks::Mechanized. One of the easiest ones to work with is just eluding me. Specifically, I'm updating the method that parses the Monastery's XML thread ticker returning a concise but useful datastructure.

The problem is that the datastructure returned by XML::Twig (and previously XML::Simple) isn't as simple as it should be; it contains extra levels of indirection that are unneeded.

It wouldn't be all that hard to simply traverse the structure returned by XML::Twig, modifying the datastructure to remove extra indirection, but somehow I believe XML::Twig is capable of giving me what I want in the first place. But over the past few days I've convinced myself that I don't understand XML::Twig enough to get the most out of this highly flexible module.

Here is a simplified snippet of code that gives an example of what I'm doing.

use strict; use warnings; use XML::Twig; use Data::Dumper; my $xml; { local $/ = ''; $xml = <DATA>; } print $xml, "\n"; my $twig = XML::Twig->new(); $twig->safe_parse( $xml ); my $struct = $twig->simplify( forcearray => 1, keyattr => [ qw/id/ ], # group_tags => { 'node id' => 'id' }, ); print Dumper $struct; __DATA__ <?xml version="1.0" encoding="ISO-8859-1"?> <thread id="504929"> <node id="504941"> </node> <node id="504942"> <node id="504950"> <node id="504964"> </node> </node> <node id="504953"> </node> </node> <node id="504944"> </node> </thread>

As you can see, I've commented out the group_tags attribute, because it wasn't gaining me anything, at least how I was using it.

The output I'm getting is:

$VAR1 = { 'node' => { '504942' => { 'node' => { '504953' => undef, '504950' => { 'node' => { '504964' => undef } } } }, '504941' => undef, '504944' => undef } };

I'm close, but what I really want is:

$VAR1 = { '504942' => { '504953' => undef, '504950' => { '504964' => undef } }, '504941' => undef, '504944' => undef };

In other words, the node => {... is extra indirection that I don't need or want.

Any tips on how to coax this out of XML::Twig?


Dave