使用XML :: Twig进行属性比较

时间:2014-07-10 13:31:30

标签: perl xml-twig

我有像这样的巨大xml文件:

  <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>

如果CONFORMATION为“O”,我必须打印“FEE”和“GROUP_ID”的值,如果构造是“I”,我必须在单独的行中打印它。

我使用了以下程序,我得到了这个

的帮助
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";

    }

}

打印两个值后 它显示错误,因为所有标签都不相同并显示错误 不能在未定义的值上调用方法第一个子。

这是因为所有“first_child”都不相似。

请帮忙。

1 个答案:

答案 0 :(得分:2)

将处理程序更改为List

CONFORMATION使用$conformation

使用DATA检查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";
        }
    }
}