hotshot has asked for the wisdom of the Perl Monks concerning the following question:
This XML holds a menus tree and available commands in each menu. I parse the file using the Objects style like that:<level name="Exanet admin" value="1"> <menu cliname="NFS" clicmd="nfs"> <menu cliname="Exports" clicmd="exports"> <command clicmd="add" state="nfsExportsAdd"/> <command clicmd="edit" state="nfsExportsEdit"/> <command clicmd="view" state="nfsExportsView"/> </menu> <menu cliname="Configure" clicmd="configure"> <command clicmd="set" state="nfsConfigSet"/> <command clicmd="view" state="nfsConfigView"/> </menu> </menu> </level>
I want to be able to print this menu to the user (on Unix, not to browser necessarily), therefore I have to iterate recursively on $xml returned from parsefile, something like:my $parser = new XML::Parser(Style => 'Objects'); my $xml = $parser->parsefile('test.xml');
from what I read, there can be only hash refs, array refs and hash objects inside $xml.&printXML($xml); sub printXML { my $ref = shift; if (ref($ref) eq 'HASH') { print "Type: HASH\n"; while (($key, $val) = each(%{$ref})) { print "key: $key, val: $val\n"; &printXML($val); } } elsif (ref($ref) eq 'ARRAY') { # kids print "Type: ARRAY\n"; for (@{$ref}) { print "bla: $_\n"; &printXML($_); } } elsif ($xml->isa('HASH')) { # elements print "Type: hash object\n"; while (($key, $val) = each(%{$ref})) { print "key: $key, val: $val\n"; &printXML($val); } } else { # text print $ref, "\n"; } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Parsing XML
by mirod (Canon) on Nov 26, 2002 at 12:37 UTC | |
by grantm (Parson) on Nov 26, 2002 at 19:57 UTC |