output HTML from XML via Transformer - Java XML

Java examples for XML:XSLT

Description

output HTML from XML via Transformer

Demo Code


//package com.java2s;
import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerFactory;

import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import javax.xml.transform.OutputKeys;
import org.w3c.dom.Node;
import org.w3c.dom.Document;

import java.io.Writer;

public class Main {
    public static void outputHTML(Node e, Writer w) throws Exception {
        outputHTML(e, w, 4);//  w ww.j av a  2  s . co m
    }

    public static void outputHTML(Node e, Writer w, int indent)
            throws Exception {
        TransformerFactory tf = TransformerFactory.newInstance();
        tf.setAttribute("indent-number", new Integer(4));
        Transformer xformer = tf.newTransformer();

        if (e instanceof Document) {
            w.write("<!DOCTYPE html>\n");
        }
        DOMSource source = new DOMSource(e);
        StreamResult result = new StreamResult(w);
        xformer.setOutputProperty(OutputKeys.METHOD, "html");
        xformer.setOutputProperty(OutputKeys.INDENT, "yes");
        xformer.transform(source, result);
    }
}

Related Tutorials