#! /usr/bin/perl

#
# SAX version of XML::Template. Advantages over DOM: Doesn't have to load
# the entire thing into memory, and you can chain filters. Disadvantages:
# Slightly kludgier interface.
#
# Differences from the DOM version:
# 
# - There is no process(). Instead, it works as a SAX filter, so you put it
#   in the stream, usually between a parser and a writer (ie.
#   parser -> XML::TemplateSAX::Handler -> writer). process_file works as
#   before, but it returns a _string_, not a DOM tree.
# - You can no longer insert a DOM tree. Instead, what you have is -- FIXME:
#   figure out this :-)
#

use XML::SAX::Expat;
use XML::SAX::Writer;

package XML::TemplateSAX::Handler;
use base qw(XML::SAX::Base);

sub new {
	my $class = shift;
	my %options = @_;

	my $self = {
		obj => $options{'Content'},
		Handler => $options{'Handler'}
	};
	bless($self, $class);
	return $self;
}

sub start_element {
	my ($self, $data) = @_;

	$self->SUPER::start_element($data);
}

package XML::TemplateSAX;

sub process_file {
	my ($filename, $obj, $clean) = @_;

	my $str = '';

	# FIXME: hardcoding expat = not good?
	my $writer = XML::SAX::Writer->new(Output => \$str);
	my $filter = XML::TemplateSAX::Handler->new(Handler => $writer, Content => $obj);
	my $parser = XML::SAX::Expat->new(Handler => $filter);
	$parser->parse_file($filename);

	return $str;
}

1;
