user3805574
user3805574

Reputation: 69

attribute comparision using XML::Twig

I am having huge xml file like this:

  <List NAME="ANDREW" ENROLED="2" FEE="640" CONFORMATION="I"> 
     <DATA>
       <HOUSE>
        <PRIMARY GROUP_ID="37496" SECTION="A"/>
        <PRIMARY GROUP_ID="37496" SECTION="B"/>
       </HOUSE>
      </DATA>
     </List>
     <List NAME="SAM" ENROLED="4" FEE="640"  CONFORMATION="O">
      <DATA>
       <HOUSE>
        <PRIMARY GROUP_ID="36816" SECTION="A"/>
        <PRIMARY GROUP_ID="36816" SECTION="B"/>
       </HOUSE>
      </DATA>
     </List>
     <List NAME="RAY" ENROLED="1" FEE="982"   CONFORMATION="O">
      <ADDRESS>
       <STREET>
        <PRIMARY GROUP_ID="36892" SECTION="A"/>
        <PRIMARY GROUP_ID="36892" SECTION="B"/>
       </STREET>
      </ADDRESS>
     </List>
      <List NAME="MATHEW" ENROLED="3" FEE="467" CONFORMATION="I">
     <DATA>
       <HOUSE>
        <PRIMARY GROUP_ID="37436" SECTION="A"/>
        <PRIMARY GROUP_ID="37436" SECTION="B"/>
       </HOUSE>
      </DATA>
     </List>
     <List NAME="RAY" ENROLED="1" FEE="982"   CONFORMATION="O">
      <ADDRESS>
       <STREET>
        <PRIMARY GROUP_ID="36892" SECTION="A"/>
        <PRIMARY GROUP_ID="36892" SECTION="B"/>
       </STREET>
      </ADDRESS>
     </List>

i have to print the value of "FEE" and "GROUP_ID" if the CONFORMATION IS "O" and if the conformation is "I" i have to print that in separate line.

i have used following program i got help for this

XML::Twig;

my $phraser = XML::Twig->new(twig_handlers => {API_PORT => \&process_list});
$phraser -> parsefile("FS_CONF.xml");

sub process_list 
{
    my ( $twig, $list ) = @_;
    my $conformation = $list -> att( 'LIST' ); 

 my $fee = $list -> att ( 'FEE' );
    foreach my $primary ( $list -> first_child ( 'DATA' ) -> first_child ('HOUSE') -> children() )
    {
        my $group_id = $primary -> att ( 'GROUP_ID' );
        print "$conformation, $fee, $group_id\n";

    }

}

after getting printed two values it is showing error because all the tags are not same and showing error can't call method first child on undefined value.

this is comming because of all the "first_child" are not similar.

please help.

Upvotes: 0

Views: 68

Answers (1)

toolic
toolic

Reputation: 62236

Change your handler to List.

Use CONFORMATION for $conformation.

Check for the DATA tag with defined.

use warnings;
use strict;
use XML::Twig;

my $phraser = XML::Twig->new( twig_handlers => { List => \&process_list } );
$phraser->parsefile("FS_CONF.xml");

sub process_list {
    my ( $twig, $list ) = @_;
    my $conformation = $list->att('CONFORMATION');
    my $fee = $list->att('FEE');
    if (defined $list->first_child('DATA')) {
        foreach my $primary ( $list->first_child('DATA')->first_child('HOUSE')->children() ) {
            my $group_id = $primary->att('GROUP_ID');
            print "$conformation, $fee, $group_id\n";
        }
    }
}

Upvotes: 2

Related Questions