#! /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;
use XML::TemplateSAX::Buffer;
use XML::TemplateSAX::Cleaner;
use XML::TemplateSAX::Handler;

package XML::TemplateSAX;

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

	my ($writer, $cleaner, $filter, $parser);
	my $str = '';

	# FIXME: hardcoding expat = not good?
	$writer = XML::SAX::Writer->new(Output => \$str);

	if ($clean) {
		$cleaner = XML::TemplateSAX::Cleaner->new(Handler => $writer, Content => $obj);
		$filter = XML::TemplateSAX::Handler->new(Handler => $cleaner, Content => $obj);
	} else {
		$filter = XML::TemplateSAX::Handler->new(Handler => $writer, Content => $obj);
	}

	$parser = XML::SAX::Expat->new(Handler => $filter);
	$parser->parse_file($filename);

	return $str;
}

1;
