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

I currently have XML::Simple and XML::Writer installed on my box. Can I use either of these to read in the attribute value from the following XML file (I know it is simple but I didn't really want to come off all complicated!)
<Begin> <Here ID=4>This is the start...</Here> <There REF=5>This is the middle...</There> </Begin>
How would I read in the values of ID and REF to a value of $value1 and $value2. Thanks for any of your help with this. peace dez L

Replies are listed 'Best First'.
Re: How can I read in XML Attributes.
by mirod (Canon) on Sep 06, 2001 at 23:50 UTC

    XML::Simple is what you are looking for here. The best way to work with it is to use Data::Dumper (or Data::Denter) extensively:

    #!/bin/perl -w use strict; use XML::Simple; use Data::Dumper; my $doc= XMLin( './file.xml'); # you need to specify the path to the f +ile print Dumper( $doc);

    Then you can start figuring out where the different parts of your XML go.

    If you have repeated elements (several There for exemple) then you might want to have a look at the forcearray option. Play with it, experiment, read the doc (perldoc XML::Simple), read the review, search (and Super Search) on XML::Simple to find how other people use it here.

    Good luck!

Re: How can I read in XML Attributes.
by runrig (Abbot) on Sep 06, 2001 at 23:53 UTC
    What you have is not valid XML without quotes around the '4' and '5'. But you can parse like so:
    use strict; use XML::Simple; use Data::Dumper; my $xml = <<EOT; <Begin> <Here ID="4">This is the start...</Here> <There REF="5">This is the middle...</There> </Begin> EOT my $xs = XML::Simple->new; my $data = $xs->XMLin($xml); print "$data->{Here}{ID}\n"; print "$data->{There}{REF}\n"; print Dumper($data);
    Update: And read the docs as mirod suggests to possibly get the data structure produced more to your liking.

    Its up to you whether you want to use the functional interface as mirod did, or the OO interface as I did. XMLin() calls new() when called functionally, so if you're parsing many documents in a script, its better IMO to call new() once (possibly with some options) to get a parsing object, then parse all the documents with that one object. If you're only parsing one document in a script, then you may as well use the functional interface.

      Sorry about the oversight of "s around the attributes. Thanks for your help however. peace dez L