使用JDOM处理XML数据之XSLT篇(二)
我们用一个javabean来实现对XML文档的格式化。
XSLTFilter.java
package XML;
import java.io.*;
import java.util.*;
import org.jdom.*;
import org.jdom.output.*;
import org.jdom.transform.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
public class XSLTFilter {
private Document outputDoc;
private String stylesheetPath;
private Document doc=null;
public XSLTFilter() {}
public void setoutputDoc(Document s) {
this.outputDoc=s;
}
public void setStylePath(String s) {
this.stylesheetPath=s;
}
public void startFilter() {
try {
TransformerFactory myFactory = TransformerFactory.newInstance();
Transformer myTransformer = myFactory.newTransformer(new StreamSource(stylesheetPath));
JDOMResult result = new JDOMResult();
myTransformer.transform( new JDOMSource( outputDoc ), result );
doc = result.getDocument();
} catch (Exception e) {
System.out.println("Error was:" + e.getMessage());
}
}
public void destroy() {}
public Document getXmlDoc(){
return(doc);
}
}
这个javabean输入一个JDOM文档格式,输入一个XSLT文档的位置,输出格式化好的文档。
然后用一个jsp来调用这个javabean
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="org.jdom.*" %>
<%@ page import="org.jdom.output.*" %>
<%@ page import="org.jdom.input.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import="XML.*" %>
<%
String fileName="watchlist.xml";
String aa=getServletContext().getRealPath("/")+"jdom\\";
String trace=aa+fileName;
String styleName="watchlist.xsl";
String styleTrace=aa+styleName;
String resultName="aa.html";
String resultTrace=aa+resultName;
XML.readXML readXmlBean = new XML.readXML();
Document doc;
readXmlBean.readXML(trace);
doc=readXmlBean.getXmlDoc();
XML.XSLTFilter XSLTFilter =new XML.XSLTFilter();
XSLTFilter.setoutputDoc(doc);
XSLTFilter.setStylePath(styleTrace);
XSLTFilter.startFilter();
doc=XSLTFilter.getXmlDoc();
XML.writeXML writeXmlBean = new XML.writeXML();
writeXmlBean.writeXML(doc,resultTrace);
%>
文中用到的readXML和writeXML参见 :
http://www.csdn.net/Develop/read_article.asp?id=20720