/**
 * 
 */
package org.ajax4jsf.builder.xml;

import java.io.StringWriter;

import javax.xml.transform.ErrorListener;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.ajax4jsf.builder.config.ParsingException;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.NodeList;


/**
 * @author Maksim Kaszynski
 *
 */
public class XMLBodySerializer {
	public String serialize(NodeList childNodes, Document xmlDocument) throws ParsingException {
		try {
			StringWriter out;
			DocumentFragment fragment = xmlDocument.createDocumentFragment();
			for (int i = 0; i < childNodes.getLength(); i++) {
				fragment.appendChild(childNodes.item(i).cloneNode(true));
			}
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			transformer.setErrorListener(new ErrorListener(){

				public void error(TransformerException exception)
						throws TransformerException {
				}

				public void fatalError(TransformerException exception)
						throws TransformerException {
				}

				public void warning(TransformerException exception)
						throws TransformerException {
				}
				
			});
			transformer.setOutputProperty("indent", "yes");
			transformer.setOutputProperty("omit-xml-declaration", "yes");
			out = new StringWriter();
			StreamResult result = new StreamResult(out);
			transformer.transform(new DOMSource(fragment), result);
			return out.toString();
		} catch (Exception e) {
			throw new ParsingException(e);
		}
	}
}
