Java 怎么使用javax.xml.transform包将XML文档转换为其他文档格式

2019年7月30日22:58:53Java 怎么使用javax.xml.transform包将XML文档转换为其他文档格式已关闭评论 1,150 1460字阅读4分52秒

1.简介

Java 怎么使用javax.xml.transform包将XML文档转换为其他文档格式?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Main {

  public void run(String xmlFile, String xslFile, String outputFile)
      throws FileNotFoundException, TransformerConfigurationException,
      TransformerException {
    InputStream xslInputStream = new FileInputStream(xslFile);
    Source xslSource = new StreamSource(xslInputStream);
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer(xslSource);
    InputStream xmlInputStream = new FileInputStream(xmlFile);
    StreamSource in = new StreamSource(xmlInputStream);
    StreamResult out = new StreamResult(outputFile);
    transformer.transform(in, out);

  }

  public static void main(String[] args) {
    String fileName = null;
    String fileName2 = null;
    String fileName3 = null;
    fileName = "patients.xml";
    fileName2 = "patients.xsl";
    fileName3 = "patients.html";
    Main app = new Main();
    try {
      app.run(fileName, fileName2, fileName3);
    } catch (FileNotFoundException ex) {
      ex.printStackTrace();
    } catch (TransformerConfigurationException ex) {
      ex.printStackTrace();
    } catch (TransformerException ex) {
      ex.printStackTrace();
    }
  }
}

 
继续阅读
编程十万个怎么办