Java XML Document convert to String via Transformer

Description

Java XML Document convert to String via Transformer

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;
import org.w3c.dom.Element;

public class Main {
   public static void main(String args[]) {
      try {//from w  ww . j  a va 2 s .  co m
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         DocumentBuilder parser = factory.newDocumentBuilder();
         Document doc = parser.parse("data.xml");
         Element root = doc.getDocumentElement();
         TransformerFactory tFactory = TransformerFactory.newInstance();
         Transformer transformer = tFactory.newTransformer();
         
         StringWriter sw = new StringWriter();  
         StreamResult result = new StreamResult(sw);  
         DOMSource source = new DOMSource(root);  
         transformer.transform(source, result); 
         String xmlString = sw.toString();  
         System.out.println(xmlString);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}



PreviousNext

Related