i have below xml file , trying parse it
<books> <book name="first" feed="contentfeed" mode="modes" /> <book name="first" feed="communityfeed" mode="modes" region="1"/> <book name="second" feed="contentfeed" mode="" /> <book name="second" feed="communityfeed" mode="modes" /> <book name="second" feed="articlefeed" mode="modes" /> </books>
i using perl version 5.8 xml::simple
. below code have written
use xml::simple; $xs = new xml::simple( keyattr => { book => 'name' } , forcearray => [ 'book','name' ] ); $config = $xs->xmlin( <complete path xml file> );
below result (displayed using data::dumper
)
'book' => { 'first' => { 'feed' => 'communityfeed', 'mode' => 'modes', 'region' => '1' }, 'second' => { 'feed' => 'articlefeed', 'mode' => 'modes' }, }
instead have output in format below
'book' => { 'first' => { 'communityfeed' => { mode => 'modes', region => '1' }, 'contentfeed' => { mode => 'modes' } }, 'second' => { 'communityfeed' => { mode => 'modes' }, 'contentfeed' => { mode => '' }, 'articlefeed' => { mode => 'modes' } }, }
notes
- the xml file format cannot changed current production version
- perl version 5.8 preferred version used in parent script , parsing logic should merged script
have encountered kind of issue before? if how can tackled?
xml::simple
awkward , frustrating module use, , doubt if can persuade build data structure require. other xml parser step forward
here's solution using xml::twig
. can interrogate parsed xml data , build whatever data structure it
i've used data::dump
display resulting data
use strict; use warnings 'all'; use xml::twig; $config; { $twig = xml::twig->new; $twig->parsefile('books.xml'); $book ( $twig->findnodes('/books/book') ) { $atts = $book->atts; ( $name, $feed ) = delete @{$atts}{qw/ name feed /}; $config->{book}{$name}{$feed} = $atts; } } use data::dump; dd $config;
output
{ book => { first => { communityfeed => { mode => "modes", region => 1 }, contentfeed => { mode => "modes" }, }, second => { articlefeed => { mode => "modes" }, communityfeed => { mode => "modes" }, contentfeed => { mode => "" }, }, }, }