Formatting an XML file using Transformer : Transformer « XML « Java Tutorial






import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
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.xml.sax.InputSource;

public class Main {
  public static void main(String[] argv) throws Exception {
  }

  static void formatXMLFile(String file) throws Exception{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(new InputStreamReader(new FileInputStream(
        file))));

    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.setOutputProperty(OutputKeys.METHOD, "xml");
    xformer.setOutputProperty(OutputKeys.INDENT, "yes");
    xformer.setOutputProperty("b;http://xml.apache.org/xsltd;indent-amount", "4");
    xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    Source source = new DOMSource(document);
    Result result = new StreamResult(new File(file));
    xformer.transform(source, result);
  }
}








33.11.Transformer
33.11.1.Source for the JAXP Transformation Application
33.11.2.Source for Transforming DOM Node to HTML with JAXP
33.11.3.Catch TransformerException
33.11.4.Transforming an XML File with XSL into a DOM Document
33.11.5.Applying XSLT Stylesheets
33.11.6.Create an XML file and attach an XSL
33.11.7.And now to attach an XSL
33.11.8.Formatting an XML file using Transformer