perl beginer...help with how to parse a xml file

Discussion in 'Perl' started by newbie_10, Jun 6, 2011.

  1. newbie_10

    newbie_10 New Member

    Joined:
    Jun 6, 2011
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    student
    Hi,

    I want to take an xml file and recognize a particular tag and print what is in between that tag.
    How can I refer to something that is nested?

    Example: Books.xml
    <Books>

    <Book>
    <title>Perl Magic</title>
    <author>Karthik</author>
    <publisher>ORielly</publisher>
    <price currency="Rupees" value="330"/>
    </Book>

    <Book>
    <title>Perl for Dummies</title>
    <author>Mark</author>
    <publisher>ORielly</publisher>
    <price currency="Rupees" value="420"/>
    </Book>

    </Books>

    Perl script : books.pl

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

    $xml = new XML::Simple;

    $data = $xml->XMLin("books.xml");

    print "$data->{author} is the author of $data->{title} and it is published by $data->{publisher}\n"


    I'm not getting the correct output for this. What am I missing?
     
  2. newbie_10

    newbie_10 New Member

    Joined:
    Jun 6, 2011
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    student
    I want the output like:

    Karthik is the author of Perl Magic and it is published by ORielly.
    Mark is the author of Perl for Dummies it is published by ORielly.


    Can someone help me out?? please..

    Thanks in advance
     
  3. sakthiwin2004

    sakthiwin2004 New Member

    Joined:
    Jul 2, 2012
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Senior Software Engineer
    Location:
    Bangalore
    Home Page:
    http://www.go4expert.com/forums/profile.php
    use the following code,

    print "$data->{Book}->[0]->{author} is the author of $data->{Book}->[0]->{title} and it is published by $data->{Book}->[0]->{publisher}\n"
    print "$data->{Book}->[1]->{author} is the author of $data->{Book}->[1]->{title} and it is published by $data->{Book}->[1]->{publisher}\n"

    instead of print "$data->{author} is the author of $data->{title} and it is published by $data->{publisher}\n"

    Note: Suppose, input has 100 <Book> you are using the loop accordingly.

    Thanks
    Sakthi
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice