java中使用xls格式化xml的实例

在java中调用xls格式化xml

使用javax.xml.transform.Transformer,将xml用xls格式化为另一种xml

输入为xml字符串,输出也为xml字符串,代码模板如下:

Java代码 

//这里使用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(); 
  } 
} 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!