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

Monks:

I'm working on my first perl/xml project (using XML::Simple) and am in desperate need of help. I don't even have sample code I'm proud enough of to show.

I'm trying to parse the following xml config:
<?xml version="1.0" encoding="utf-8"?> <config> <host1> <process name="proc1" /> <process name="proc2" /> <process name="proc3" /> <process name="proc4" /> </host1> <host2> <process name="proc5" /> <process name="proc6" /> <process name="proc7" /> <process name="proc8" /> </host2> </config>

The XML config is a list of all of our servers and what processes they're running. I'm given this XML config and have no say over how it's structured.

What I need to be able to do is query the XML config for a particular host (host1, host2, etc.) and have it return the processes (proc1, proc2, etc.).

Thanks in advance.

- Justin

Replies are listed 'Best First'.
Re: Parsing XML w/ Attributes
by jrsimmon (Hermit) on Dec 19, 2007 at 20:38 UTC
    Proud or not, post what you've got so that you're not just asking us to do your work for you. A couple of tips would be to make sure you've read the doc on XML::Simple, especially pertaining to the ForceArray option.
      Fair enough :-P

      Between posting and now I've come up with the following code which seems to work:
      #!/usr/bin/perl -w use strict; use XML::Simple; my ($ref); $ref = XMLin('file.xml'); foreach (sort keys %{$ref->{'host1'}->{'process'}}) { print "proc: $_\n"; }

      Is this the best way to be doing this?

      - Justin
        I would encourage you to use ForceArray. Even if it's not necessary here, down the road you'll almost certainly be glad you started out using it. This is how I would go about what you're doing, using ForceArray.
        #!/usr/bin/perl -w use strict; use XML::Simple; my $parser = new XML::Simple(ForceArray => 1); my $ref = $parser->XMLin('c:\temp\file.xml'); foreach my $host (keys(%$ref)){ foreach my $proc (keys(%{$ref->{$host}[0]->{process}})){ print "$proc is running on $host\n"; } }
Re: Parsing XML w/ Attributes
by pajout (Curate) on Dec 19, 2007 at 22:54 UTC
    Perhaps XML::Trivial could help you:
    #!/usr/bin/perl use XML::Trivial; use strict; use warnings; foreach my $hostelm (XML::Trivial::parseFile('file.xml')->{0}->ea) { foreach ($hostelm->ea) { print "Host: ".$hostelm->en." Process: ".$_->ah('name')."\n" if $_->en eq 'process'; } }