Java HTML / XML How to - Apply XSLT onto XML files








Question

We would like to know how to apply XSLT onto XML files.

Answer

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
//from w  w w  .  j  a v a  2s. c o m
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Main {
  public static void main(String[] args) throws Exception {
    File dir = new File("Input Directory Root Path Here");
    listFilesInDirectory(dir);
  }

  public static void listFilesInDirectory(File dir) throws Exception {
    String tempfolder = System.getProperty("java.io.tmpdir");
    String pathRequiredForFile = null;
    File[] files = dir.listFiles();
    if (files == null) {
      return;
    }
    for (File f : files) {
      if (f.isDirectory()) {
        pathRequiredForFile = f.getName();
        listFilesInDirectory(f);
      } else {
        System.out.println(f.getName());
        File path = new File(tempfolder + "//" + pathRequiredForFile);
        path.mkdir();
        OutputXml(f, path.getAbsolutePath());
      }
    }
  }

  public static void OutputXml(File in, String saveFileInPath) throws Exception {
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Source xslDoc = new StreamSource("backup.xslt");
    Source xmlDoc = new StreamSource(in.getPath());
    System.out.print(in.getName() + "/n");
    String outputFileName = in.getName().split("\\.")[0];
    System.out.println(outputFileName);
    OutputStream htmlFile;
    htmlFile = new FileOutputStream(saveFileInPath + "//" + outputFileName
        + ".html");

    Transformer transformer = tFactory.newTransformer(xslDoc);
    transformer.transform(xmlDoc, new StreamResult(htmlFile));
  }
}