java中利用javax.xml.transform.Transformer將xml通過xsl樣式轉化成html

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);
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章