一个用java解析xsl文件小例子

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);
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);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值