日期:2014-05-17  浏览次数:20657 次

xml转html例子2
xml转为html
2010-05-04 13:29
依据一定的格式把xml转为html,要用到xsl。xsl语法可以在网上找详细资料。现贴出代码:

java类(我是通过一个http去访问的)

package web;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;

public class XmlToHtmlAction extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 1L;

public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
   String xmlContent = this.getFileContent("F:/szworkspace/play/WebRoot/xsl/cd_catalog.xml");
   String xslContent = this.getFileContent("F:/szworkspace/play/WebRoot/xsl/cd_catalog.xsl");
   /*xslContent = "<?xml version=\"1.0\" ?>";
  
   xslContent +="<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/TR/WD-xsl\">";
   xslContent +="</xsl:stylesheet>";*/
   try{
    String html = this.xmlToHtml(xslContent, xmlContent);
    response.getWriter().print(html);
   }catch(Exception e){
    e.printStackTrace();
   }
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
   doPost(request,response);
 
}

/**
* @desc 获得文件内容,可能会有编码问题
* @param fileName 文件路径
   * */
private String getFileContent(String fileName) {
   StringBuilder strContent = new StringBuilder();
   BufferedReader bis = null;
   try {
    File file = new File(fileName);
    bis = new BufferedReader(new InputStreamReader(new FileInputStream(
      file),"GBK"));
    String line = null;
    while ((line = bis.readLine()) != null) {
     strContent.append(line).append("\n");
    }

   } catch (Exception e) {
    e.printStackTrace();
   } finally {
    if (bis != null) {
     try {
      bis.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
   }
   return strContent.toString();
}

/**
* @desc 将xml字符串转换为html
* @param bosXslSou xsl内容
* @param bosXmlSou xml内容
* */
private String xmlToHtml(String xslContent, String xmlContent) throws TransformerException {
  StringReader bosXslSou = new StringReader(xslContent);
   StringReader bosXmlSou = new StringReader(xmlContent);
   TransformerFactory tFactory = TransformerFactory.newInstance();
   // 获取xsl的字符流
   Transformer transformer = tFactory.newTransformer(new javax.xml.transform.stream.StreamSource(bosXslSou));
   Properties properties = transformer.getOutputProperties();
 &nbs