Solved

Convert xml to hash in perl

Posted on 2008-10-27
3
1,946 Views
Last Modified: 2012-08-13
This is the continuation of
http://www.experts-exchange.com/Programming/Languages/Scripting/Perl/Q_23837595.html

I was wondering if its possible to build a hash back from the xml that got generated. Will this hash match the original hash?

Basically,  I wanted to build a hash from a string and convert the hash to xml format. This is working so far with the code below. Now I want to see if it's possible to build a hash(hash of hash) back from this xml and will it look same as the original hash.

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
 
my @str = (";&EVENT[__nmi_0](nmi, THREAD => 0, TRIGGER => &TRIGGER[__nmi_0.trigger](eom, LIP => 0x2020, SELF_CHECK => 'MUST_COMPLETE', THREAD => 0));",
          ";&EVENT[__psmi_1](psmi, THREAD => 0, TRIGGER => &TRIGGER[__retire_1](retire, LIP => 0x203f, TRIGGER => &EVENT[__smi_1](smi, THREAD => 1, TRIGGER => &TRIGGER[__eom_1](eom, LIP => 0x203f, THREAD => 0))));",
          ";&EVENT[__psmi_0](psmi, THREAD => 0, TRIGGER => &TRIGGER[__psmi_0.trigger](eom, LIP => 0x2000, SELF_CHECK => 'MUST_COMPLETE', THREAD => 0));" );


 
my %Event;
my %Pieces;
foreach (@str) {
      %Pieces = ();
      my $Cnt;
     
      1 while s/\&(\w+)\[__([^\]]+)\]\((\w+),\s+([^\(\)]+)\)/$Cnt++;$Pieces{$Cnt}=MakeHash($1,$2,$3,$4);"$2:SubHash{$Cnt}"/ge;
      for my $piece (sort {$b <=> $a} keys %Pieces) {
            while(my ($k, $v) = each %{$Pieces{$piece}}) {
                  if($v =~ /^(.*):SubHash{(\d+)}$/) {
                        $Pieces{$piece}->{$k}=$1;
                        $Pieces{$piece}->{$1}=$Pieces{$2};
                  }
            }
      }
      if(/^;(.*):SubHash{(\d+)};$/) {
            $Event{$1}=$Pieces{$2};
      }
}
 
print XMLout(\%Event);
 
sub MakeHash {
      return {lc($_[0])=> $_[2], split(/[,=>\s]+/, $_[3])};
}
 
sub XMLout {
      my ($ref, $pre) = @_;
      $pre='' unless defined($pre);
      
      my $str='';
      if(ref($ref) eq 'HASH') {
            foreach my $k (sort keys %$ref) {
                  $str .= "$pre<param name=$k>\n";
                  if(ref($ref->{$k})) { $str .= XMLout($ref->{$k},"$pre\t"); }
                  else { $str .= "$pre\t<value val=$ref->{$k} />\n"; }
                  $str .= "$pre</param>\n";
            }
      }
      else {
            die "Unsupported reference: " . ref($ref) . "\n";
      }
      return $str;
}

0
Comment
Question by:Anu2117
3 Comments
 
LVL 39

Accepted Solution

by:
Adam314 earned 500 total points
ID: 22815509
You can use XML::Simple to read the XML.
my $hash = XMLin($filename);

Open in new window

0
 
LVL 26

Expert Comment

by:wilcoxon
ID: 25953867
I would suggest changing your script to use XML::Simple for both writing the XML and reading it back.  XML::Simple converts perl hash to XML (XMLout) and XML to perl hash (XMLin).

As Adam314 said, getting the perl hash from the XML is just:

my $hash = XMLin($filename);  # $filename can also be a string

I would suggest looking at the XML::Simple documentation as there are quite a few useful options to both XMLin and XMLout.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Trying to use two loops in a perl script but not getting results need. 10 82
stftime format 4 55
perl to convert excel to csv 3 181
Perl modules on linux ec2 3 95
I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This is a video describing the growing solar energy use in Utah. This is a topic that greatly interests me and so I decided to produce a video about it.

929 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now