赞
踩
http://vbtboy.iteye.com/blog/619058
注意,需要你自己新建一个下面代码中出现的目录,
d:\study\xml2html\xsl
d:\study\xml2html\xml
d:\study\xml2html\result
然后放入你写好的xsl文件和xml在对应的目录下面,运行main方法就可以了。
代码如下:
- package openjaw;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileWriter;
-
- import javax.xml.transform.Transformer;
- import javax.xml.transform.TransformerFactory;
- import javax.xml.transform.stream.StreamResult;
- import javax.xml.transform.stream.StreamSource;
-
- public class XSLT_XML_HTML {
-
- public static String[] ExecuteXSL() {
- try {
- String[] xmlfiles = getXmlFilePath();
- String[] content = new String[xmlfiles.length];
- int i = 0;
- for (String xmlfile : xmlfiles) {
- ByteArrayOutputStream byteRep = new ByteArrayOutputStream();
- TransformerFactory transformerFactory = TransformerFactory
- .newInstance();
- StreamSource source = new StreamSource(xmlfile);
- StreamResult result = new StreamResult(byteRep);
- StreamSource style = new StreamSource(getXslFilePath());
- Transformer transformer = transformerFactory
- .newTransformer(style);
- transformer.setOutputProperty(
- javax.xml.transform.OutputKeys.ENCODING, "utf-8"); // \u8BBE\u7F6E\u7F16\u7801
- transformer.transform(source, result);
- content[i] = byteRep.toString();
- i++;
- }
- return content;
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
-
- }
-
- public static String getXslFilePath() {
- File file = new File("D:\\study\\xsl2xml\\xsl");
- File files[] = file.listFiles();
- String filename = "";
- String filepath = "";
- for (File f : files) {
- filename = f.getName();
- if (filename.indexOf("xsl") != -1) {
- filepath = f.getAbsolutePath();
- break;
- }
- }
- return filepath;
- }
-
- public static String[] getXmlFilePath() {
- File file = new File("D:\\study\\xsl2xml\\xml");
- File files[] = file.listFiles();
- String filename = "";
- String[] filepath = new String[files.length];
- for (int i = 0; i < files.length; i++) {
- File f = files[i];
- filename = f.getName();
- if (filename.indexOf("xml") != -1) {
- filepath[i] = f.getAbsolutePath();
- }
- }
- return filepath;
- }
-
- public static void createFile(String[] contents) {
- try {
- for (int i = 0; i < contents.length; i++) {
- File newFile = new File("D:\\study\\xsl2xml\\result\\" + i+".html");
- if (!newFile.exists()) {
- newFile.createNewFile();
- }
- FileWriter fw = new FileWriter(newFile);
- fw.write(contents[i]);
- fw.close();
- }
- } catch (Exception e) {
- // TODO: handle exception
- }
-
- }
-
- public static void main(String args[]) {
- String contents[] = ExecuteXSL();
- for (String content : contents) {
- System.out.println(content);
- }
- createFile(contents);
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。