#! /usr/bin/perl
#
# $Header: //sapdb/TOOLSRC/develop/sys/src/BuildPackage/XMLParser.pm#1 $
# $DateTime: 2002/02/19 16:40:04 $
# $Change: 16574 $
#
# Desc: 
#	- parser of pcr_releases.xml
#	- specify XML handlers to generate XML tree

package BuildPackage::XMLParser;

use Exporter;
use XML::Parser::Expat;
use GME::XMLElement;

@ISA = ('Exporter');

@EXPORT = ('new', 'ParseFile', 'ParseStream');

my %ParserHash;

sub new {
	my $self = {};
	bless $self;

	$self->{Parser} = new XML::Parser::Expat;
	$self->{Parser}->setHandlers (
	        Start  => \&HandleStart,
       		Char   => \&HandleChar,
	        End    => \&HandleEnd );
	$self->{Current} = 0;
	$self->{Parent} = 0;
	$self->{Tree} = 0;

	$ParserHash{$self->{Parser}} = $self;
	return $self;
}

sub ParseFile {
	my $self = shift;
	my $filename = shift;	
	$self->{Parser}->parsefile ($filename);
	return $self->{Tree};
}

sub ParseStream {
	my $self = shift;
	my $fh_ref = shift;	
	undef $bla;
	XML::Parser::Expat::ParseStream 
		($self->{Parser}->{Parser}, $fh_ref, $bla);
	return $self->{Tree};
}

sub HandleStart {
	my ($ExpatParser, $Type, %Attr) = @_;
	my $Parser = $ParserHash{$ExpatParser};
	$Parser->{Current} = XMLElement->new ($Type);        	
	if ($Type eq 'sap_db_releases') {
		# set root of tree
		$Parser->{Tree} = $Parser->{Current};
	}
	else{
		$Parser->{Current}->SetParent ($Parser->{Parent});	
	}
	foreach my $attrib (keys(%Attr)){
		$Parser->{Current}->SetAttribute($attrib, $Attr{$attrib});
	}
	$Parser->{Parent} = $Parser->{Current};
}

sub HandleEnd {
	my ($ExpatParser, $Type) = @_;
	my $Parser = $ParserHash{$ExpatParser};;
	$Parser->{Current}->Insert();
	$Parser->{Parent} = $Parser->{Current}->GetParent();
	$Parser->{Current} = $Parser->{Parent};
}

sub HandleChar {
	my  ($ExpatParser, $Content) = @_;
	my $Parser = $ParserHash{$ExpatParser};;

	# don't care empty Content
	return unless ($Content =~ /\S/);

	$Content =~ /(\S+)/;
	$Parser->{Current}->SetContent ($1);
}

1;

