转载:http://aguu125.iteye.com/blog/580766
项目EDI里有一个写xslt解析xml并输出xml的功能
xslt里有调用到java类方法,测试不方便就上网找了些资料
用java类来调用xslt进行解析并输出
所用的jar库
1.Apache xalan-j_2_7_0
新建一个java类项目
加入以下jar包
新建一个调用解析类(与例子程序SimpleTransform类一样)
package com.aguu.translate; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; public class SimpleTrans { public static void main(String[] args) throws TransformerException, TransformerConfigurationException, FileNotFoundException, IOException { // Use the static TransformerFactory.newInstance() method to instantiate // a TransformerFactory. The javax.xml.transform.TransformerFactory // system property setting determines the actual class to instantiate -- // org.apache.xalan.transformer.TransformerImpl. TransformerFactory tFactory = TransformerFactory.newInstance(); // Use the TransformerFactory to instantiate a Transformer that will work with // the stylesheet you specify. This method call also processes the stylesheet // into a compiled Templates object. Transformer transformer = tFactory.newTransformer(new StreamSource("ECMCONTAINERREPAIR_2_IMIS_CNSHA_MAP.XSLT")); // Use the Transformer to apply the associated Templates object to an XML document // (foo.xml) and write the output to a file (foo.out). transformer.transform(new StreamSource("AUTO-IMIS_ER_EXCEL_FROMAT_2007032E.xls.xml"), new StreamResult(new FileOutputStream("result.xml"))); System.out.println("************* The result is in birds.out *************"); } }
解析类就完成了。。。
=========================================
xml,xslt编写
xslt中引入java类
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:java="class所在文件夹" exclude-result-prefixes="java">
命名空间java了,所在类路径可以是相对或绝对,如:d://com/package或是“com.package”
注意:使用可选属性xsl:exclude-result-prefixes,预防了java命名空间被包括到结果文件中。
调用:
//这里是静态方法 <xsl:value-of select="java:类.方法"/> <xsl:if test="java:类.方法"/> //如果有参数,String类型 〈xsl:value-of select="java:Reverse.reverse(´This is a test´)" /〉 <!--静态变量--> 〈xsl:value-of select="java:Reverse.reverse(./Description)" /〉<!--元素值--> 〈xsl:value-of select="java:Reverse.reverse($varString)" /〉<!--定义的变量--> //如果需要实例化类(尚未跑通) <xsl:variable name="funvalue" select="mynspace.classname.new()"/>
杯具了,发现Eclipse3.5的javaee版本自身就带了个xslt转换的插件还可以debugg。。