AlexPham AlexPham - 6 months ago 14
Perl Question

XML::Simple in perl, with mixed xml file

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

Answer

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";
}