xsl转换xml,带格式输出。
import java.io.ByteArrayOutputStream;
import java.io.File;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
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;
/**
*
* @param SourceXmlFile 源文件路径
* @param xslFile xsl文件路径
* @param targetXmlFile 格式化后生成的目标文件路径
*/
public static void Transform(String SourceXmlFile, String xslFile, String targetXmlFile) {
try {
TransformerFactory tFac = TransformerFactory.newInstance();
Source xslSource = new StreamSource(xslFile);
Transformer transformer = tFac.newTransformer(xslSource);
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
File sourceFile = new File(SourceXmlFile);
File targetFile = new File(targetXmlFile);
Source source = new StreamSource(sourceFile);
Result result = new StreamResult(targetFile);
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
/**
*
* @param xmlFile xml文件路径
* @param xslFile xls文件路径
* @return 格式化后的xml字符串
*/
public static String formatXml(String xmlFile, String xslFile) {
try {
ByteArrayOutputStream byteRep = new ByteArrayOutputStream();
StreamResult result = new StreamResult(byteRep);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
StreamSource source = new StreamSource(xmlFile);
StreamSource style = new StreamSource(xslFile);
Transformer transformer = transformerFactory.newTransformer(style);
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); // \u8BBE\u7F6E\u7F16\u7801
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.transform(source, result);
return byteRep.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
转换后的格式: