|
javax.xml.transform.Templates是一个编译过的xsl, 线程安全, 可以从其中得到transformer. 在server端做xslt转换的BS架构中可以明显提高效率.
//模板缓存 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); }
|