1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

How to read xml file line by line and extract a particular tag???

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

  1. newbie_10

    newbie_10 New Member

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

    <xml>
    <title> Sample </title>
    <heading1> PERL </heading1>
    <body>
    <code>

    <heading2> Definition 1: </heading2> 
    Perl is a high-level, general-purpose, interpreted, dynamic programming language. Information from <link> google.com</link>

    <heading3> Definition 2: </heading3>
    A program language that is considered public domain and hence not technically supported by a vendor. Is very popular due to the fact that it is free. Many claim that it is easier to use than JAVA and JAVA's predecessor C++. Information from <link> state.tn.us</link>

    </code>
    </body>
    </xml>

    How to extract the tag <link> from the file by reading line by line. Guide me how to go about it?

    And what changes would I have to make if I wanted the output as:
    Definition1:
    link name

    Definition2:
    link name
     
  2. Sketch-

    Sketch- New Member

    Joined:
    Jul 1, 2011
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    PHP:
    #!/usr/bin/perl -w
    my $file "file.xml"# Replace this with your xml file
    my $line 0;
    open(XML$file);
    my @xml = <XML>;
    close(XML);
    my $a 1;
    foreach 
    $line(@xml) {
    if(
    $line =~ m/<link>(.*?)<\/link>/i) {
    print 
    "Definition $a\n$1\n";
    $a++;
    }
    }
    This outputs

    Code:
    Definition 1
    google.com
    Definition 2
    state.tn.us
    
    Hope this helps!

    Remember to replace the $file variable with the name of your xml file.
     

Share This Page