
// 		      Lunanbay Software License

//  Copyright (c) 2002 Lunanbay Limited

//   This software is provided 'as-is', without any express or implied
//   warranty.  In no event will the authors be held liable for any
//   damages arising from the use of this software.

//   Permission is granted to anyone to use this software for any
//   purpose, including commercial applications, and to alter it and
//   redistribute it freely, subject to the following restrictions:

//   1. The origin of this software must not be misrepresented; you must
//      not claim that you wrote the original software. If you use this
//      software in a product, an acknowledgement in the product
//      documentation would be appreciated but is not required.

//   2. Altered source versions must be plainly marked as such, and must
//      not be misrepresented as being the original software.

//   3. This notice may not be removed or altered from any source
//      distribution.


// NB This file was substantially derived from
// http://developer.java.sun.com/developer/technicalArticles/xml/mapping/

import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;

public class XMLMapping extends DefaultHandler
{ 
	public void startDocument ()
		throws SAXException
	{
		System.out.println ("<?xml version=\"1.0\"?>");  
	}
	
	public void endDocument ()
		throws SAXException
	{
		System.out.println ();
	}
	
	public void startElement(String namespaceURI,
				 String localName,
				 String qName,
				 Attributes attr)
		throws SAXException
	{
		System.out.print ("<" + localName);

		int first = 1;
		for (int i = 0; i < attr.getLength(); i++)
		{
			if (first == 1)
			{
				first = 0;
				System.out.print (" ");
			}
			 System.out.print (attr.getLocalName(i) + "=\"" + attr.getValue(i) + "\"");
		}
		System.out.print (">");
	}
	
	public void endElement (String namespaceURI,
				String localName,
				String qName)
		throws SAXException
	{
		System.out.print ("</" + localName + ">");
	}
	
	public void characters( char[] ch, int start, int length )
		throws SAXException
	{ 
		//System.out.print ("[" + start + ":" + length + ":" + ch.toString () + "]");

		try {
			OutputStreamWriter outw = new OutputStreamWriter(System.out);
			outw.write( ch, start,length );
			outw.flush();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		// System.out.print ("]");
	}
	
	public static void main (String[] argv)
	{
		String filename = "test-1.xml";
		if (argv.length == 1)
		{
			filename = argv[0];
		}
		
		try {     
			XMLReader xr = XMLReaderFactory.createXMLReader ();

			xr.setContentHandler (new XMLMapping ());

			xr.parse (new InputSource(new FileReader (filename)));
			
		}
		catch (Exception e)
		{
			System.err.println (e.getMessage ());
		}
	}          
}             
