Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML::Simple in perl, with mixed xml file

Tags:

xml

perl

I have an DEMO.xml file look like this.

<?xml version="1.0"?>
<data>
<pattern>123456</pattern>
<pattern>654321</pattern>
<pattern>abcdefg</pattern>
<pattern owners="alex">heloworld</pattern>
<pattern owners="alex">perlprogramming</pattern>
</data>

This is my perl code to parse this file:

use XML::Simple;
use strict;
use Data::Dumper;

my $xml = new XML::Simple;
my $data = $xml->XMLin("DEMO.xml");
print Dumper($data);

And here is what I got:

$VAR1 = {
          'pattern' => [
                       '123456',
                       '654321',
                       'abcdefg',
                       {
                         'owners' => 'alex',
                         'content' => 'heloworld'
                       },
                       {
                         'owners' => 'alex',
                         'content' => 'perlprogramming'
                       }
                     ]
        };

May I know if I just simply print out the content of xml tag, what should I do ?

The expected output might look like:

123456
654321
acdefg
heloworld
perlprogramming

Thank you so much!

Alex

like image 518
AlexPham Avatar asked May 09 '16 10:05

AlexPham


2 Answers

Rule one of using XML::Simple: Don't, use something else.

I like XML::Twig and your problem looks like this:

#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

my $twig = XML::Twig -> new -> parsefile('DEMO.xml'); 
foreach my $pattern ( $twig -> get_xpath ('//pattern') ) {
   print $pattern -> text,"\n";
}
like image 135
Sobrique Avatar answered Nov 22 '22 13:11

Sobrique


Yeah. Don't use XML::Simple.

I'd do it with XML::LibXML and a bit of XPath.

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use XML::LibXML;

my $parser = XML::LibXML->new();
my $doc = $parser->parse_file(shift);

print $doc->findvalue('//text()');

Which does this:

$ perl xml2text test.xml

123456
654321
abcdefg
heloworld
perlprogramming
like image 43
Dave Cross Avatar answered Nov 22 '22 15:11

Dave Cross