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);
}
