in reply to Accessing xml elements using XML::Parser module

For playing with Perl data structures, read: perldoc perldsc

I used XML::Parser before I was aware of parsers which use method calls to extract information, such as XML::Twig. It was worth the investment in time for me to switch.

use warnings; use strict; use XML::Twig; my $str = ' <booklist> <book type="technical"> <author>Book 1 author 1</author> <author>Book 1 author 2</author> <title>Book 1 title</title> <isbn>Book1ISBN</isbn> </book> <book type="fiction"> <author>Book 2 author 1</author> <author>Book 2 author 2</author> <title>Book 2 title</title> <isbn>Book2ISBN</isbn> </book> <book type="technical"> <author>Book 3 author 1</author> <author>Book 3 author 2</author> <author>Book 3 author 3</author> <title>Book 3 title</title> <isbn>Book3ISBN</isbn> </book> </booklist> '; my $t = XML::Twig->new( twig_handlers => { book => \&book }, ); $t->parse($str); sub book { my ($t, $book) = @_; print $book->field('title'), ": "; print $book->att('type'), "\n"; } __END__ Book 1 title: technical Book 2 title: fiction Book 3 title: technical

Replies are listed 'Best First'.
Re^2: Accessing xml elements using XML::Parser module
by uday_sagar (Scribe) on Feb 16, 2012 at 04:58 UTC
    hey, its awesome! thank you. I have slightly modified my xml.
    <booklist> <book type="technical"> <author mainpage = "simple" finalpage = "style" ><author1>Book 1 + author1 1</author1></author> <author>Book 1 author 2</author> <title>Book 1 title</title> <isbn>Book1ISBN</isbn> </book> <book type="fiction"> <author>Book 2 author 1</author> <author>Book 2 author 2</author> <title>Book 2 title</title> <isbn>Book2ISBN</isbn> </book> <book type="technical"> <author>Book 3 author 1</author> <author>Book 3 author 2</author> <author>Book 3 author 3</author> <title>Book 3 title</title> <isbn>Book3ISBN</isbn> </book> </booklist>
    how can i access author1 field now?
      how can i access author1 field now?
      • Read the documentation; I already provided the link to you.
      • Look at my code, and try to understand how it works.
      • Modify the code I provided; this change should be straightforward.