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
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";
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With