利用JDK1.4中的Templates实现xslt转换的缓存
发表于:2007-07-04来源:作者:点击数:
标签:
java x.xml.transform.Templates是一个编译过的xsl, 线程 安全 , 可以从其中得到transformer. 在server端做xslt转换的BS架构中可以明显提高效率. //模板缓存 static private Hashtable templates = new Hashtable(); public static Transformer getTransform
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);
}
原文转自:http://www.ltesting.net