下载一个jdom.jar文件(在www.jdom.org可以找到),下面的代码是读取一个xml文件,并解析后response到browser。xml文件封装为Document。具体的使用方法可以在网站上找到import org.jdom.*;public class test{ /** 读入XML模板,建立对应的树,并以org.jdom.Document的形式返回 @param fileName @return org.jdom.Document */ public static Document readXML(String fileName) { try { SAXBuilder builder = new SAXBuilder(); Document anotherDocument = builder.build(new java.io.File (fileName)); return anotherDocument; } catch(JDOMException e) { e.printStackTrace(); } catch(NullPointerException e) { e.printStackTrace(); } return null; } /** 完成XSL对XML的解析,并把结果输出到Response中 @param xslFile @param xmlDoc @param response @return boolean */ public static boolean ExecuteXSL(String xslFile, Document xmlDoc, HttpServletResponse response) { try { TransformerFactory tFactory = TransformerFactory.newInstance(); // Make the input sources for the XML and XSLT documents org.jdom.output.DOMOutputter outputter = new org.jdom.output.DOMOutputter(); org.w3c.dom.Document domDocument = outputter.output(xmlDoc); javax.xml.transform.Source xmlSource = new javax.xml.transform.dom.DOMSource(domDocument); javax.xml.transform.stream.StreamSource xsltSource = new javax.xml.transform.stream.StreamSource(new FileInputStream( xslFile)); //Make the output result for the finished document javax.xml.transform.stream.StreamResult xmlResult = new javax.xml.transform.stream.StreamResult(response.getOutputStream()); Transformer transformer = tFactory.newTransformer(xsltSource); // transformer.setOutputProperty("encoding","GBK") ; transformer.transform(xmlSource, xmlResult); } catch(FileNotFoundException e) { e.printStackTrace(); return false; } catch(TransformerConfigurationException e) { e.printStackTrace(); return false; } catch(TransformerException e) { e.printStackTrace(); return false; } catch(org.jdom.JDOMException e) { e.printStackTrace(); return false; }catch(Exception e){ e.printStackTrace(); return false; } return true; } }
/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, Lotus * Development Corporation., http://www.lotus.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package servlet;import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.net.URL;import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.*; import org.apache.xerces.dom.*; import javax.xml.parsers.*;/* * This sample applies the todo.xsl stylesheet to the * todo.xml XML document, and returns the transformation * output (HTML) to the client browser. * * IMPORTANT: For this to work, you must place todo.xsl and todo.xml * in the servlet root directory for documents. * */public class SimpleXSLTServlet extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); } public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, java.net.MalformedURLException { // The servlet returns HTML. response.setContentType("text/html; charset=GB2312"); // Output goes in the response stream. PrintWriter out = response.getWriter(); try { TransformerFactory tFactory = TransformerFactory.newInstance(); // Get the XML input document and the stylesheet. // Source xmlSource = new StreamSource(new URL("file:Domain_Configure.xml").openStream()); Source xmlSource = new DOMSource(getDOM()); Source xslSource = new StreamSource(new URL("file:fooparam.xsl").openStream()); // Generate the transformer. Transformer transformer = tFactory.newTransformer(xslSource); // Perform the transformation, sending the output to the response. transformer.transform(xmlSource, new StreamResult(out)); } catch (Exception e) { out.write(e.getMessage()); e.printStackTrace(out); } out.close(); } public Document getDOM() throws Exception { Document dReturn = null; Element eList = null; DocumentBuilderFactory ne=DocumentBuilderFactory.newInstance(); DocumentBuilder dr=ne.newDocumentBuilder(); dReturn = dr.newDocument(); //首先创建实体DOM的列表节点 eList = dReturn.createElement("doc"); dReturn.appendChild(eList); eList.appendChild(dReturn.createTextNode("中华人民共和国")); //将各个属性值付到节点中 return (dReturn); } }
如何通过Xalan来生成 HTML 由 XML 和 XSL /** TestValidate.java** Created on 2002ū3?20?, ??3:55*/package clientApp;import javax.xml.parsers.SAXParserFactory;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerFactory;import javax.xml.transform.sax.SAXSource;import javax.xml.transform.stream.StreamResult;import javax.xml.transform.stream.StreamSource;import org.xml.sax.InputSource;import org.xml.sax.SAXException;import org.xml.sax.SAXParseException;import org.xml.sax.XMLReader;import org.xml.sax.helpers.DefaultHandler; import java.io.FileInputStream;import java.io.FileOutputStream;import javax.ejb.*;import javax.naming.*;import javax.rmi.*;import java.util.*;import java.io.*;import java.sql.*;import net.lancetech.fire.mail.enterprise.*;import net.lancetech.fire.mail.vo.*;/**** @author user*/public class ValidateXMLInput {public static void main(String[] args)throws Exception {ValidateXMLInput v = new ValidateXMLInput();v.validate();} void validate()throws Exception {// Since we're going to use a SAX feature, the transformer must support// input in the form of a SAXSource.TransformerFactory tfactory = TransformerFactory.newInstance();if(tfactory.getFeature(SAXSource.FEATURE)) {// Standard way of creating an XMLReader in JAXP 1.1.SAXParserFactory pfactory= SAXParserFactory.newInstance();pfactory.setNamespaceAware(true); // Very important!// Turn on validation.pfactory.setValidating(true); //要设置DTD验证,要打开此开关// Get an XMLReader.XMLReader reader = pfactory.newSAXParser().getXMLReader(); // Instantiate an error handler (see the Handler inner class below) that will report any// errors or warnings that occur as the XMLReader is parsing the XML input.Handler handler = new Handler(); //此捕捉错误的类在下面定义reader.setErrorHandler(handler); // Standard way of creating a transformer from a URL.Transformer t = tfactory.newTransformer(new StreamSource(new FileInputStream("/export/home/user/lm/EJB/clientApp/MailList.xsl"))); //得到XSL// Specify a SAXSource that takes both an XMLReader and a URL.SAXSource source = new SAXSource(reader,new InputSource(new FileInputStream("/export/home/user/lm/EJB/clientApp/test_xml2.xml"))); //得到XML //SAXSource source = new SAXSource(reader,new InputSource(new StringReader(ValidateXMLInput.getXMLStrFromEJB()))); //得到XML(可动态生成 e.g. 由EJB生成) //由于源代码中寻找DTD的方法,在此设置DTD所在的路径,XML中要带有DTD声明System.setProperty("user.dir","/export/home/user/lm/EJB/clientApp");//-----------------------------// Transform to a file.try {//可将PrintWriter 直接放在 StreamResult中,可直接输出到页面t.transform(source, new StreamResult(new FileOutputStream("/export/home/user/lm/EJB/clientApp/birds.out")));}catch (TransformerException te) {// The TransformerException wraps someting other than a SAXParseException// warning or error, either of which should be "caught" by the Handler.System.out.println("Not a SAXParseException warning or error: " + te.getMessage());} System.out.println("=====Done=====");}elseSystem.out.println("tfactory does not support SAX features!");} // Catch any errors or warnings from the XMLReader.class Handler extends DefaultHandler {public void warning(SAXParseException spe)throws SAXException {System.out.println("SAXParseException warning: " + spe.getMessage());} public void error(SAXParseException spe)throws SAXException {System.out.println("SAXParseException error: " + spe.getMessage());}}}
/**
读入XML模板,建立对应的树,并以org.jdom.Document的形式返回
@param fileName
@return org.jdom.Document
*/
public static Document readXML(String fileName)
{
try {
SAXBuilder builder = new SAXBuilder();
Document anotherDocument = builder.build(new java.io.File (fileName));
return anotherDocument;
} catch(JDOMException e) {
e.printStackTrace();
} catch(NullPointerException e) {
e.printStackTrace();
}
return null;
}
/**
完成XSL对XML的解析,并把结果输出到Response中
@param xslFile
@param xmlDoc
@param response
@return boolean
*/
public static boolean ExecuteXSL(String xslFile, Document xmlDoc, HttpServletResponse response)
{
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
// Make the input sources for the XML and XSLT documents
org.jdom.output.DOMOutputter outputter = new org.jdom.output.DOMOutputter();
org.w3c.dom.Document domDocument = outputter.output(xmlDoc);
javax.xml.transform.Source xmlSource = new javax.xml.transform.dom.DOMSource(domDocument);
javax.xml.transform.stream.StreamSource xsltSource =
new javax.xml.transform.stream.StreamSource(new FileInputStream( xslFile)); //Make the output result for the finished document
javax.xml.transform.stream.StreamResult xmlResult =
new javax.xml.transform.stream.StreamResult(response.getOutputStream()); Transformer transformer = tFactory.newTransformer(xsltSource);
// transformer.setOutputProperty("encoding","GBK") ; transformer.transform(xmlSource, xmlResult);
}
catch(FileNotFoundException e) {
e.printStackTrace();
return false;
} catch(TransformerConfigurationException e) {
e.printStackTrace();
return false;
} catch(TransformerException e) {
e.printStackTrace();
return false;
} catch(org.jdom.JDOMException e) {
e.printStackTrace();
return false;
}catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
}
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, Lotus
* Development Corporation., http://www.lotus.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package servlet;import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.net.URL;import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.apache.xerces.dom.*;
import javax.xml.parsers.*;/*
* This sample applies the todo.xsl stylesheet to the
* todo.xml XML document, and returns the transformation
* output (HTML) to the client browser.
*
* IMPORTANT: For this to work, you must place todo.xsl and todo.xml
* in the servlet root directory for documents.
*
*/public class SimpleXSLTServlet extends HttpServlet { public void init(ServletConfig config) throws ServletException
{
super.init(config);
} public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException, java.net.MalformedURLException
{
// The servlet returns HTML.
response.setContentType("text/html; charset=GB2312");
// Output goes in the response stream.
PrintWriter out = response.getWriter();
try
{
TransformerFactory tFactory = TransformerFactory.newInstance();
// Get the XML input document and the stylesheet.
// Source xmlSource = new StreamSource(new URL("file:Domain_Configure.xml").openStream());
Source xmlSource = new DOMSource(getDOM());
Source xslSource = new StreamSource(new URL("file:fooparam.xsl").openStream());
// Generate the transformer.
Transformer transformer = tFactory.newTransformer(xslSource);
// Perform the transformation, sending the output to the response.
transformer.transform(xmlSource, new StreamResult(out));
}
catch (Exception e)
{
out.write(e.getMessage());
e.printStackTrace(out);
}
out.close();
}
public Document getDOM() throws Exception {
Document dReturn = null;
Element eList = null;
DocumentBuilderFactory ne=DocumentBuilderFactory.newInstance();
DocumentBuilder dr=ne.newDocumentBuilder();
dReturn = dr.newDocument(); //首先创建实体DOM的列表节点
eList = dReturn.createElement("doc");
dReturn.appendChild(eList);
eList.appendChild(dReturn.createTextNode("中华人民共和国")); //将各个属性值付到节点中
return (dReturn);
}
}
/** TestValidate.java** Created on 2002ū3?20?, ??3:55*/package clientApp;import javax.xml.parsers.SAXParserFactory;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerFactory;import javax.xml.transform.sax.SAXSource;import javax.xml.transform.stream.StreamResult;import javax.xml.transform.stream.StreamSource;import org.xml.sax.InputSource;import org.xml.sax.SAXException;import org.xml.sax.SAXParseException;import org.xml.sax.XMLReader;import org.xml.sax.helpers.DefaultHandler; import java.io.FileInputStream;import java.io.FileOutputStream;import javax.ejb.*;import javax.naming.*;import javax.rmi.*;import java.util.*;import java.io.*;import java.sql.*;import net.lancetech.fire.mail.enterprise.*;import net.lancetech.fire.mail.vo.*;/**** @author user*/public class ValidateXMLInput {public static void main(String[] args)throws Exception {ValidateXMLInput v = new ValidateXMLInput();v.validate();}
void validate()throws Exception {// Since we're going to use a SAX feature, the transformer must support// input in the form of a SAXSource.TransformerFactory tfactory = TransformerFactory.newInstance();if(tfactory.getFeature(SAXSource.FEATURE)) {// Standard way of creating an XMLReader in JAXP 1.1.SAXParserFactory pfactory= SAXParserFactory.newInstance();pfactory.setNamespaceAware(true); // Very important!// Turn on validation.pfactory.setValidating(true); //要设置DTD验证,要打开此开关// Get an XMLReader.XMLReader reader = pfactory.newSAXParser().getXMLReader();
// Instantiate an error handler (see the Handler inner class below) that will report any// errors or warnings that occur as the XMLReader is parsing the XML input.Handler handler = new Handler(); //此捕捉错误的类在下面定义reader.setErrorHandler(handler);
// Standard way of creating a transformer from a URL.Transformer t = tfactory.newTransformer(new StreamSource(new FileInputStream("/export/home/user/lm/EJB/clientApp/MailList.xsl"))); //得到XSL// Specify a SAXSource that takes both an XMLReader and a URL.SAXSource source = new SAXSource(reader,new InputSource(new FileInputStream("/export/home/user/lm/EJB/clientApp/test_xml2.xml"))); //得到XML
//SAXSource source = new SAXSource(reader,new InputSource(new StringReader(ValidateXMLInput.getXMLStrFromEJB()))); //得到XML(可动态生成 e.g. 由EJB生成)
//由于源代码中寻找DTD的方法,在此设置DTD所在的路径,XML中要带有DTD声明System.setProperty("user.dir","/export/home/user/lm/EJB/clientApp");//-----------------------------// Transform to a file.try {//可将PrintWriter 直接放在 StreamResult中,可直接输出到页面t.transform(source, new StreamResult(new FileOutputStream("/export/home/user/lm/EJB/clientApp/birds.out")));}catch (TransformerException te) {// The TransformerException wraps someting other than a SAXParseException// warning or error, either of which should be "caught" by the Handler.System.out.println("Not a SAXParseException warning or error: " + te.getMessage());}
System.out.println("=====Done=====");}elseSystem.out.println("tfactory does not support SAX features!");}
// Catch any errors or warnings from the XMLReader.class Handler extends DefaultHandler {public void warning(SAXParseException spe)throws SAXException {System.out.println("SAXParseException warning: " + spe.getMessage());}
public void error(SAXParseException spe)throws SAXException {System.out.println("SAXParseException error: " + spe.getMessage());}}}