//模板缓存
static private Hashtable templates = new Hashtable();
public static Transformer getTransformer(Source xslSource)
throws Exception
{
Transformer transformer = null;
String id = xslSource.getSystemId();
if (null != id){
synchronized(templates){
Templates temp = (Templates)templates.get(id);
if (null != temp){
// System.out.println("use cache: "+id);
return temp.newTransformer();
}
}
}
TransformerFactory factory = TransformerFactory.newInstance();
Templates temp = factory.newTemplates(xslSource);
if (null != id)
synchronized(templates){
templates.put(id,temp);
}
transformer = factory.newTransformer(xslSource);
return transformer;
}
public static void transform(Source xmlSource, Source xslSource, Writer result, String encoding)
throws Exception
{
if (xmlSource == null || xslSource == null || result == null)
throw new NullPointerException("Null XSLT input");
Transformer transformer = this.getTransformer(xslSource);
transformer.setOutputProperty("encoding", encoding);
// System.out.println("xfmr: "+transformer);
StreamResult transformResult = new StreamResult(result);
transformer.transform(xmlSource, transformResult);
}
文章来源于领测软件测试网 https://www.ltesting.net/