Java XML Transformer create string from DOM tree

Description

Java XML Transformer create string from DOM tree

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 {//w ww.  j  a v a2 s.c  o  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