使用javax.xml.transform.Transformer,将xml用xls格式化为另一种xml
输入为xml字符串,输出也为xml字符串,代码模板如下:
Java代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
//这里使用xml-apis.jar实现javax.xml.transform.Transformer
import javax.xml.transform.Transformer;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class TransformXmlByXls{
private Transformer transformer;
public String handleXml(){
String sourceXml= "..." ;
StringWriter sw = new StringWriter();
InputStream in= new ByteArrayInputStream(sourceXml
.getBytes( "UTF-8" ));
transformerXslImpl(..., "UTF-8" );
transformer.transform(in, sw);
String targetXml = sw.toString();
return targetXml;
}
private transformerXslImpl(File xslTemplateFile, String encoding)
throws Exception {
initTransformerFactory();
transformer = getXslTransformerTemplate(xslTemplateFile);
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
}
private Transformer getXslTransformerTemplate(File xslFile)
throws TransformerFactoryConfigurationError,
TransformerConfigurationException {
TransformerFactory tFactory = TransformerFactory.newInstance();
Templates translet = tFactory.newTemplates( new StreamSource(xslFile));
return translet.newTransformer();
}
}
|
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://forrest420.iteye.com/blog/1186979