XML node to String by Transformer - Java XML

Java examples for XML:XSLT

Description

XML node to String by Transformer

Demo Code


//package com.java2s;
import java.io.StringWriter;
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.w3c.dom.Node;

public class Main {
    public static String node2String(Node n) {
        try {//w w w. ja  v  a2 s . c o  m
            TransformerFactory tfactory = TransformerFactory.newInstance();
            Transformer transformer = tfactory.newTransformer();
            StringWriter sw = new StringWriter();
            transformer.transform(new DOMSource(n), new StreamResult(sw));
            return sw.toString();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";

    }
}

Related Tutorials