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

Is there a way to parse a particular field for a certain element? Currently I'm using substr, but I think there is a better way of doing it.
foreach my $xml_file (@dipfile) { my $ref = XML::Simple::XMLin($xml_file, SuppressEmpty => ''); my ($default_name) = $ref->{defaultName}; my ($doc_type) = '1'; my ($default_description) = $ref->{defaultDescription}; my ($report_time) = $ref->{reportExecutionTime}; my ($reportSearchPath) = $ref->{reportSearchPath}; #Example of data in XML field /content/folder[@name='Opertations'] +/report[@name='Daily Deposit Correction'] my $temp = substr($reportSearchPath,22,11); if (substr($reportSearchPath,24,11) eq 'Operations') { $doc_type = 2; }
Thanks, Dave

Replies are listed 'Best First'.
Re: Parse XML Field
by toolic (Bishop) on May 26, 2009 at 23:15 UTC
    If the string you are looking for is guaranteed to be at position 24 and be 11 characters long, then substr is appropriate.

    Otherwise, using a regular expression might be a more general solution. If you provide a few more examples of your data, you will probably get more advice.

    Despite your node title, your question seems to have nothing to do with XML parsing. If you can provide a very small sample of your actual XML file, again, you will probably get more advice.

Re: Parse XML Field
by ww (Archbishop) on May 26, 2009 at 23:43 UTC
    Is there some reason not to use regexen?

    if ( $some_var =~ /'Opertations'/ ) { # Opertations? ;-) $doc_type = 2; }

    where $some_var contains the actual data, not a reference thereto.

    At least one advantage would be that you need not know in advance where 'Opertations' appears. That could also be a disadvantage, if there's any possibility it will occur elsewhere in a different context.

      Thanks for your guys input. I just wanted to make sure I was on the right track. I wasn't sure if there wasn't a better way to break down the XML field any further.