# ---------------------------------------------------------
# ULD2XML                                                  
# Umwandlung von ULD-Exportdateien in standardisiertes XML 
# Lizenz: GPL                                              
# (c) Martin Raspe, Bibliotheca Hertziana, 2004            
# ---------------------------------------------------------

# --------------------
package ULD::xmlwriter;
# --------------------

# SAX wrapper for XML Writer

use strict;

#use base "XML::SAX::Base";
use base "XML::Writer";
use IO;
use IO::String;

my ($opt, $level, $indent, $root, $outfile);

# --------------------
sub new {
# --------------------
my $class = shift;
$opt = shift;
my $xmlstring = shift;
my $xmlfile = $opt->{xml_file};
if ($xmlfile) {		# write to XML file
	$outfile = IO::File->new(">$xmlfile") 
		or die("Konnte XML-Datei '$xmlfile' nicht anlegen: $!\n");
	}
elsif (defined $xmlstring) {		# write to Scalar if XML file is missing
	$outfile = IO::String->new($xmlstring) 
		or die("Konnte Variable nicht zum Schreiben öffnen: $!\n");
	}
else { $outfile = undef };	# write to STDOUT if XML file is missing		
my $self = $class->SUPER::new(
	OUTPUT		=> $outfile,
	DATA_MODE 	=> !$opt->{nolines},
	DATA_INDENT	=>  $opt->{indent} || 2,
	UNSAFE		=> 1,
	);
return $self;
}

# --------------------
sub start_document {
# --------------------
$root = $opt->{root} || 'root';
}

# --------------------
sub end_document {
# --------------------
my ($self) = @_;
$outfile->close() if $outfile;
}

# --------------------
sub xml_decl {
# --------------------
my ($self, $data) = @_;
$self->SUPER::xmlDecl($data->{Encoding}, $data->{Standalone});
}

# --------------------
sub start_element {
# --------------------
my ($self, $data) = @_;
$self->SUPER::startTag($data->{Name}, %{$data->{Attributes}});
}

# --------------------
sub end_element {
# --------------------
my ($self, $data) = @_;
$self->SUPER::endTag($data->{Name});
}

# --------------------
sub characters {
# --------------------
my ($self, $data) = @_;
$self->SUPER::characters($data->{Data});
}

# --------------------
sub comment {
# --------------------
my ($self, $data) = @_;
$self->SUPER::comment($data->{Data});
}

# --------------------
sub open {
# --------------------
my ($self, $rootname) = @_;
$root = $rootname || $opt->{root} || 'root';
my $enc = $opt->{encoding} || "UTF-8";
$self->xmlDecl($enc, 1);
$self->comment($opt->{byline});
$self->comment($opt->{optionline});
$self->startTag($root);
}

# --------------------
sub close {
# --------------------
my ($self) = @_;
$self->endTag($root);
$self->end();
$outfile->close() if $outfile;
}

# --------------------
sub fullTag {
# --------------------
# replacement for dataElement, keeps attribute order
my ($self, $name, $data, @atts) = (@_);
$self->startTag($name, @atts);
$self->characters($data);
$self->endTag($name);
}

__FILE__
