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

I am trying to make this code work but with no luck. It does the xml parsing but it doesn't store the outcome in a new txt file. I could really use some help. Thank you!

#!/usr/bin/perl use XML::Simple; use Data::Dumper; $xml = new XML::Simple; $data = $xml->XMLin("news2Obama.txt"); open $fh_o, '>', 'new_output.xml' or die "can't open file: $!"; $fh_o = Dumper ($data); print $fh_o; close $fh_o or die "can't close file:$!";

Replies are listed 'Best First'.
Re: perl xml parsing
by choroba (Cardinal) on May 25, 2012 at 14:25 UTC
    You overwrite the file handle by
    $fh_o = Dumper ($data);
    You probably wanted to assign the output to $_ to be printed later, so replace this line with
    $_ = Dumper ($data);
    and all should work.

      I tried this out but i got an error again (could not find ParserDetails.ini in C:/Perl/site/lib/XML/SAX GLOB(0xf9def4))

      #!/usr/bin/perl use XML::Simple; use Data::Dumper; $xml = new XML::Simple; $data = $xml->XMLin("news2Obama.xml"); open $fh_o, '>', 'new_output.txt' or die "can't open file: $!"; $_ = Dumper ($data); print $fh_o; close $fh_o or die "can't close file:$!";

        From the command line run this:

        perl -MXML::SAX -e "XML::SAX->add_parser('XML::SAX::PurePerl')->save_p +arsers()"

        Also consider adding the following lines to your code:

        use strict; use warnings;

        See Use strict and warnings.

Re: perl xml parsing
by toolic (Bishop) on May 25, 2012 at 14:29 UTC
    Another way. Change:
    $fh_o = Dumper ($data); print $fh_o;
    to:
    print $fh_o Dumper($data);

      this doesn't work either. I get could not find ParserDetails.ini in C:/Perl/site/lib/XML/SAX

        The documentation for XML::Simple gives you some advice if you search for the string 'SAX':
        $XML::Simple::PREFERRED_PARSER = 'XML::Parser';
Re: perl xml parsing
by bitingduck (Deacon) on May 25, 2012 at 15:11 UTC

    I'm too lazy right now to do it with XML::Simple, but here's one I wrote a while ago to do it with XML::Parser. I wrote it to check that some XML I was writing was valid and wouldn't make the parser barf.

    #!/usr/bin/perl use strict; use warnings; use XML::Parser; $parser = new XML::Parser( Style => 'Tree' ); my $tree = $parser->parsefile( shift @ARGV ); use Data::Dumper; print Dumper( $tree );

    ADDENDUM: I usually don't bother with putting a file open/write in something this short, I just use > filename.xml