#!/usr/bin/perl -w
# Using XML::XQL
# Author: Michel Rodriguez <mirod@xmltwig.com>
# note that this code behaves slightly differently than the rest of
# the examples, some spaces are added in place. Patch welcome ;--)

use strict;
use XML::XQL;
use XML::XQL::DOM;

my $parser = XML::DOM::Parser->new();
my $doc = $parser->parsefile ("REC-xml-19980210.xml");

# get all the prods
my @prod=  $doc->xql('//prod');

# define the queries used to get the lhs and rhs from the prod
my $lhs_query = XML::XQL::Query->new (Expr => "./lhs");
my $rhs_query = XML::XQL::Query->new (Expr => "./rhs");


my $i=0;
foreach my $prod (@prod) {
        my @lhs= $lhs_query->solve( $prod); # solve the query in $prod context
        my $lhs= $lhs[0]->xql_toString;     # only one lhs

        my @rhs= $rhs_query->solve( $prod); 
        my $rhs= join( '', map { $_->xql_toString } @rhs); # maybe several rhs

        $i++;
        my $prod_text= "[$i] $lhs ::= $rhs";
        print clean( $prod_text), "\n";
}

sub clean { 
        my( $string)= @_;
        $string =~ s/\xc2\xa0/ /sg;
        $string =~ s/\s+/ /g; $string=~ s{\s$}{};
        return $string;
}
