从数据库获取数据并生成xml文档



package com.dic.prm.dm.tc.service.impl;

import java.util.Vector;
import org.jdom.Document;

import com.bsp.base.tools.XmlTranser;
import com.dic.framework.base.BaseServiceImpl;
import com.dic.prm.dm.tc.dao.DeptTreeDao;
import com.dic.prm.dm.tc.dto.DeptTreeDto;
import com.dic.prm.dm.tc.service.CreateDpTreeXmlHTMLService;
import com.dic.prm.pub.dto.UserInfoDto;
import com.dic.prm.pub.util.PrmConstants;

public class CreateDpTreeXmlHTMLServiceImpl extends BaseServiceImpl implements
  CreateDpTreeXmlHTMLService {
 private DeptTreeDao deptTreeDao;

 public DeptTreeDao getDeptTreeDao() {
  return deptTreeDao;
 }

 public void setDeptTreeDao(DeptTreeDao deptTreeDao) {
  this.deptTreeDao = deptTreeDao;
 }

 public DeptTreeDto initDeptTree(DeptTreeDto dto, UserInfoDto userDto) {

  String dept_parent = dto.getDeptTree().getdeptParent();
  String oper_no = userDto.getOper_no();
  StringBuffer sql = new StringBuffer();
  Vector result = new Vector();
  if (dept_parent != null && !"".equals(dept_parent)) {
   /* 根据上级部门查询部门列表树 */
   sql.append(" select a.dept_no,a.parent_dept_no,a.dept_type,a.dept_name,a.local_net,a.area_id,a.flag ");
   sql.append(" from "+PrmConstants.DB_ULP_USER_NAME+".info_dept a ");
   sql.append(" where a.parent_dept_no  = '" + dept_parent + "' ");
   sql.append(" order by a.flag,a.dept_name, a.dept_no");
   System.out.println(sql);
  } else {
   /* 根据用户查询部门列表树 */
   sql.append(" select dept_no,parent_dept_no,dept_type,dept_name,local_net,area_id,flag ");
   sql.append(" from "+PrmConstants.DB_ULP_USER_NAME+".info_dept");
   sql.append(" where dept_no in (select dept_no from "+PrmConstants.DB_ULP_USER_NAME+".info_oper where oper_no='"
     + oper_no + "'");
   sql.append(" union");
   sql.append(" select dept_no from "+PrmConstants.DB_ULP_USER_NAME+".rule_oper_control_dept where oper_no='"
     + oper_no + "')");
   sql.append(" order by  flag,dept_name,dept_no");
   System.out.println(sql);
  }
  // 查询数据存入Vector或数组
  result = deptTreeDao.findVectorBySQL(sql.toString());
  Document doc = null;
  // 根据sql字符串,查询取得的数据生成源XML文档
  Document sourcedoc = XmlTranser.getDocument(sql.toString(), result);
  // 源xml文档结合指定xsl生成目标xml文档
  doc = XmlTranser.transWithXsl(sourcedoc, "createDpTreeXML.xsl");
  dto.setDoc(doc);
  return dto;
 }

}

---------------------------------------------------

package com.bsp.base.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom.transform.XSLTransformer;

import com.bss.common.sysconfig.GetSystemConfig;

/**
 * <p>Title: ulp BSS System</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2006</p>
 * <p>Company: </p>
 * @author jcm
 * @version 1.2
 * 把xsl文件放到与tomcat.bat相同的文件夹
 * --ex.
 * E:\WorkDir\configs\下面
 *
 */
public class XmlTranser {
  public XmlTranser() {
  }

  /**
   * 自定义解析字符串函数
   * @param    sql  String
   * @return   a String array
   */
  public static String[] parseString(String sql) {
    String str1 = "";
    String str2 = "";
    String retArr[] = null;
    sql = sql.toUpperCase();
    if (sql.trim().startsWith("SELECT")) {
      str1 = sql.trim().substring(6);
      int temp = str1.indexOf("FROM");
      str2 = str1.substring(0, temp);
      ////Logger.getLogger("").info(str2);
      String cond[] = str2.trim().split(",");
      retArr = new String[cond.length];
      for (int j = 0; j < cond.length; j++) {
        if (cond[j].indexOf(" AS ") != -1) {
          String bb[] = cond[j].split(" AS ");
          retArr[j] = bb[1].trim();
        }
        else {
          if (cond[j].indexOf(".") != -1) {
            int idx = cond[j].indexOf(".");
            retArr[j] = cond[j].substring(idx + 1).trim();
          }
          else {
            retArr[j] = cond[j].trim();
          }
        }
      }
    }
    return retArr;
  }

  /**
   *解析写入目标文件
   * @param doc         xml文档
   * @param stylesheet   样式单
   * @param fileName    文件名
   */
  public static void transWithXsl(Document doc, String stylesheet,
                                  String fileName) {
    try {
      String xslDir = GetSystemConfig.getBIBMConfig().getExtParam("xsl_file");
      if (null == xslDir) { //
        xslDir = XmlTranser.class.getClassLoader().getResource("").getPath()+"configs/xsl/";
        Logger.getLogger("").info("use default xsl conf:\n" + xslDir);
      }
      XSLTransformer transformer = new XSLTransformer(xslDir + stylesheet);
      Document x2 = transformer.transform(doc);

      XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
      FileOutputStream output = new FileOutputStream(new File(fileName));
      outputter.output(x2, output);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * 解析返回目标xml文档
   * @param sourcedoc  源xml文档
   * @param stylesheet  指定样式单
   */
  public static Document transWithXsl(org.jdom.Document sourcedoc,
                                      String stylesheet) {
    Document retDoc = null;
    try {
      String xslDir = GetSystemConfig.getBIBMConfig().getExtParam("xsl_file");
      if (null == xslDir) { //
        xslDir = XmlTranser.class.getClassLoader().getResource("").getPath() +
            "configs/xsl/";
        Logger.getLogger("").info("use default xsl conf:\n" + xslDir);
      }
      XSLTransformer transformer = new XSLTransformer(xslDir + stylesheet);
      retDoc = transformer.transform(sourcedoc);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return retDoc;
  }

  /**
   * 从查询结果生成源XML文档函数
   * @param  String sql
   * @param  Vector result
   * @return Documnet
   */
  public static Document getDocument(String sql, Vector result) {
    //构建xml
    Element root = new Element("Tree");
    Document doc = new Document(root);
    //填充value生成tree元素
    String volName[] = XmlTranser.parseString(sql);

    for (int i = 0; i < result.size(); i++) {
      Element element = new Element("tree");
      Vector tempV = (Vector) result.get(i);

      for (int j = 0; j < tempV.size(); j++) {
        Element subelement = new Element(volName[j]);
        subelement.setText( (String) tempV.get(j));
        element.addContent(subelement);
      }
      root.addContent(element);
    }
    return doc;
  }

  /**
   * 从查询结果生成XML文档函数
   * @param String sql
   * @param String[][]
   * @return Document
   */
  public static Document getDocument(String sql, String[][] result) {
    //构建xml
    Element root = new Element("Tree");
    Document doc = new Document(root);
    //填充value生成tree元素
    String volName[] = XmlTranser.parseString(sql);
    for (int i = 0; i < result.length; i++) {
      Element element = new Element("tree");
      String[] tempV = result[i];

      for (int j = 0; j < tempV.length; j++) {
        Element subelement = new Element(volName[j]);
        subelement.setText( (String) tempV[j]);
        element.addContent(subelement);
      }
      root.addContent(element);
    }
    return doc;
  }

  /************************测试属性xsl**************************************/
  /**
   * 从查询结果生成源XML文档函数
   * @param  String sql
   * @param  Vector result
   * @return Documnet
   */
  public static Document getAttDocument(String sql, Vector result) {
    //构建xml
    Element root = new Element("Tree");
    Document doc = new Document(root);
    //填充value生成tree元素
    String volName[] = XmlTranser.parseString(sql);
    for (int i = 0; i < result.size(); i++) {
      Element element = new Element("tree");
      Vector tempV = (Vector) result.get(i);

      for (int j = 0; j < tempV.size(); j++) {
        Element subelement = new Element(volName[j]);
        //subelement.setText((String)tempV.get(j));
        Attribute attri = new Attribute(volName[j], (String) tempV.get(j));
        subelement.setAttribute(attri);
        element.addContent(subelement);
      }
      root.addContent(element);
    }
    return doc;
    //写文件
    /*XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
         FileOutputStream output = null;
         try {
      output = new FileOutputStream(new File("E:\\jcm\\jcm.xml"));
         }
         catch (FileNotFoundException ex) {
         }
         try {
      outputter.output(doc, output);
         }
         catch (IOException ex1) {
         }*/

  }

}

--------------------

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
 <xsl:element name="tree">
  <xsl:for-each select="Tree/tree">
   <xsl:element name="tree">    
      <xsl:attribute name="text"><xsl:value-of select="DEPT_NAME"/></xsl:attribute>
      <xsl:attribute name="target">DeptView</xsl:attribute>
      <xsl:attribute name="src">/agent/dm/createDpTreeXmlHTMLAction!toCreateDpTree.action?deptParent=<xsl:value-of select="DEPT_NO"/></xsl:attribute>
      <xsl:attribute name="action">javascript:getDeptNew('<xsl:value-of select="DEPT_NAME"/>', '<xsl:value-of select="DEPT_NO"/>');</xsl:attribute>
      <xsl:if test="FLAG='0'">
      <xsl:attribute name="icon">../images/xmltree/images/xp/dept.gif</xsl:attribute>
      </xsl:if>
      <xsl:if test="FLAG='1'">
      <xsl:attribute name="icon">../images/xmltree/images/xp/dept_inactive.gif</xsl:attribute>
      </xsl:if>
      <xsl:attribute name="openIcon">../images/xmltree/images/xp/deptOpen.gif</xsl:attribute>
      <xsl:attribute name="fileIcon">../images/xmltree/images/xp/deptdef.gif</xsl:attribute>       
   </xsl:element>
  </xsl:for-each>
 </xsl:element>
</xsl:template>
</xsl:stylesheet>


你可能感兴趣的:(从数据库获取数据并生成xml文档)