Solved

Convert xml to hash in perl

Posted on 2008-10-27
3
1,940 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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
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 video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

706 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

19 Experts available now in Live!

Get 1:1 Help Now