in reply to recreating an array
Your XML appears to be incomplete, hence unparseable by any decent XML parser.
The code below uses a few regexes operation over the entire string. Note this will only work if your XML is spread across several lines as shown in the snippet you provided.
use strict; # Load up your XML # This example ignores the obviously mangled <?xml ?> line at the top my $xml = qq( <GeocodeResponse> <status>OK</status> <result> <type>street_address</type> <formatted_address>1600 Amphitheatre Pkwy</formatted_address> <address_component> <long_name>1600</long_name> <short_name>1600</short_name> <type>street_number</type> </address_component> ); # Before print "Before the transformation: \n"; print "$xml\n"; # Regexes to re-write the text # replace all closing tags, which must run to the end of the line $xml =~ s[</.+$][",]mg; # rewrite opening tags in as hash keys - first part $xml =~ s[<]["]mg; # concluding part of rewriting opening tags $xml =~ s[>][" => "]mg; # handle elements that contain non-text elements $xml =~ s[=> "$][=> {]mg; # the final closing tag is surplus, remove it $xml =~ s[^\s+",\s+$][]mg; # find out how many opening braces are in the string my $count = split /{/, $xml; # close all the hashes $xml .= " } " x $count; # complete the transformation with the var declaration and the top-lev +el opening brace my $var = "\$mytable = { " . $xml; # After print "After the transformation: \n"; print "$var\n"; # define the lexical that our transformed text will be eval'ed into my $mytable; eval $var; # choke if an error occurs in the eval die "ERROR: ", $@, "\n" if $@; # load Data::Dumper to examine the resulting data structure use Data::Dumper qw(Dumper); # the whole hash of hashes (and plain text values) print "\nThe whole object:\n"; print Dumper $mytable; # an example of a nested object print "\nThe Geocode -> result -> address_component object:\n"; print Dumper $$mytable{"GeocodeResponse"}{"result"}{"address_component +"};
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: recreating an array
by Inexistence (Acolyte) on Sep 08, 2011 at 21:26 UTC |