package tools.xml;

import java.io.File;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

/**
 * Veraltet - wird nicht mehr gebraucht.
 * 
 * @author Martin
 * 
 */
public class XMLDom {

	public static Document openFile(final String filename) {
		Document doc;
		try {
			File datei = new File(filename);
			DocumentBuilderFactory fa = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = fa.newDocumentBuilder();
			doc = db.parse(datei);
		} catch (Exception e) {
			System.err.println("Fehler beim Einlesen der XML-Datei:" + e);
			doc = null;
		}
		return doc;
	}

	public static Document newDocument() {
		Document doc;
		try {
			DocumentBuilderFactory fa = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = fa.newDocumentBuilder();
			doc = db.newDocument();
		} catch (Exception e) {
			// System.err.println("Fehler beim Anlegen der XML-Date" + e);
			doc = null;
		}
		return doc;
	}

	public static void saveDocument(final Document doc, final String filename) {
		try {
			TransformerFactory fac = TransformerFactory.newInstance();
			Transformer transformer = fac.newTransformer();
			transformer.setOutputProperty("encoding", "iso-8859-1");
			transformer.setOutputProperty("indent", "yes");
			DOMSource quelle = new DOMSource(doc);
			File datei = new File(filename);
			StreamResult output = new StreamResult(datei);
			transformer.transform(quelle, output);
		} catch (Exception e) {
			System.err.println("Fehler beim Anlegen der XML-Datei " + e);
		}
	}

	public static String saveDocumentToString(final Document doc) {
		String s = "";
		try {
			StringWriter writer = new StringWriter();

			TransformerFactory fac = TransformerFactory.newInstance();
			Transformer transformer = fac.newTransformer();
			transformer.setOutputProperty("encoding", "iso-8859-1");
			transformer.setOutputProperty("indent", "yes");
			DOMSource quelle = new DOMSource(doc);

			StreamResult output = new StreamResult(writer);
			transformer.transform(quelle, output);

			s = writer.toString();

		} catch (Exception e) {
			System.err.println("Fehler beim Anlegen des XML-Strings " + e);
		}
		return s;
	}

}
