学习java&xml心得(三)

本文介绍了XMLBuilder和XMLOutput类的功能,前者将document.node对象转换为规范的xml字符串,后者用指定的string或InputStream生成文件。还讲述了在项目中用xml解决tree型权限和角色交互问题,以及实现数据库数据和xml文件同步,展示了xml在实际应用中的作用。
  XMLBuilder.class 主要是把指定的document.node对象转换成规范的xml字符串。用的是ibm的xml4j解析器.代码如下:

package com.ceic.workflow.xml;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import org.w3c.dom.Attr;
import org.w3c.dom.document.
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.ibm.xml.parsers.*;

/**
 * Title:        有效XML 字符串生成工具
 * Description:  有效XML 字符串生成工具
 * Copyright:    Copyright (c) 2003
 * Company:      国电信息中心
 * @author 张治中
 * @version 1.0
 * 有效XML 字符串生成工具
 * 例如:
 * XmlBuilder build=new XmlBuilder();
 * document.nbspdoc=((document.Class.forName("com.ibm.xml.
 * dom.document.mpl").newInstance()) 
 * ..........
 * build.printDOMTree(doc);
 * String xmlString=build.getXmlResult();
 * 再把xmlString用XmlOutput类去输出成xml文件.
 */
public class XmlBuilder
{
private String lineSeparator="/r";
private String xmlString="";
private int indentLevel=0;
protected static String STANDARD_INDENT=" ";
private String XmlHeader="<?xml version=/"1.0/" ?>";
private int currentlevel=0;
  /**
   * 生成XML字符串.
   * @param node 要生成字符串的document.其它Node.
   */
  public void printDOMTree(Node node){
 printDOMTree(node,indentLevel,false);
  }

  /**
   * 生成XML字符串.
   * @param node 要生成字符串的document.其它Node.
   * @param noTop 是否去除头尾,如果为document.象去掉<?xml.../?>头
   */
  public void printDOMTree(Node node,boolean noTop){
       printDOMTree(node,indentLevel,noTop);
  }
  /**
   * 生成XML字符串.
   * @param node 要生成字符串的document.其它Node.
   * @param level 节点的深度.(中间变量)
   * @param noTop 是否去除头尾,如果为document.象去掉<?xml.../?>头
   */
  private void printDOMTree(Node node,int level,boolean noTop)
  {
    int templevel=level;
    int find=0;
    short toptype=0;
    String topvalue="";
    int type = node.getNodeType();
    switch (type)
    {
      // print the document.nbspelement
      case Node.document.NODE:
      {
        find++;
        if(!noTop||find>1){
        xmlString+=XmlHeader+lineSeparator;
        }else{
          toptype=Node.document.NODE;
        }
        printDOMTree(((document.node).getdocument.lement(),
	 templevel+1,false);
        break;
      }

      // print element with attributes
      case Node.ELEMENT_NODE:
      { find++;

      if(!noTop||find>1){
        currentlevel=templevel;
        xmlString+=printIndent(templevel);
        xmlString+=lineSeparator+"<";
        xmlString+=node.getNodeName();
        NamedNodeMap attrs = node.getAttributes();
        for (int i = 0; i < attrs.getLength(); i++)
        {
          Node attr = attrs.item(i);
          xmlString+=" " + attr.getNodeName() +"=/"" + 
	  attr.getNodevalue() +"/"";
        }
        xmlString+=">"+lineSeparator;
      }
     else{
        toptype=Node.ELEMENT_NODE 
        topvalue="</"+node.getNodeName()+">"+lineSeparator;
        }
        NodeList children = node.getChildNodes();
        if (children != null)
      {
          int len = children.getLength();
          for (int i = 0; i < len; i++)
            printDOMTree(children.item(i),templevel+1,false);
      }

        break;
      }

      // handle entity reference nodes
      case Node.ENTITY_REFERENCE_NODE:
      {
        find++;
        xmlString+="&";
        xmlString+=node.getNodeName();
        xmlString+=";";
        break;
      }

      // print cdata sections
      case Node.CDATA_SECTION_NODE:
      {
        find++;
        xmlString+="<![CDATA[";
        xmlString+=node.getNodevalue();
        xmlString+="]]>";
        break;
      }

      // print text
      case Node.TEXT_NODE:
      {
         find++;
//        String temp=node.getNodevalue();
//        if(!temp.equals(" ")&&!temp.equals("/n")
//          &&!temp.equals("/r"))
          xmlString+=node.getNodevalue();
        break;
      }

      // print processing instruction
      case Node.PROCESSING_INSTRUCTION_NODE:
      {
        find++;
        xmlString+="<?";
        xmlString+=node.getNodeName();
        String data = node.getNodevalue();
        {
          xmlString+=" ";
          xmlString+=data;
        }
        xmlString+="?>";
        break;
      }
    }

    if (type == Node.ELEMENT_NODE)
    {
      find++;
      if(currentlevel!=templevel){
          xmlString+=printIndent(templevel);
          xmlString+=lineSeparator;
      }
      xmlString+="</";
      xmlString+=node.getNodeName();
      xmlString+=">"+lineSeparator;
    }
    if(noTop&&toptype==Node.ELEMENT_NODE){
      int len=xmlString.length() 
      int tlen=topvalue.length() 
      xmlString=xmlString.substring(0,len-tlen);
    }
  }
/**
* 生成行前的STANDARD_INDENT(一般指空格)
* @param num STANDARD_INDENT的个数
* @return String
*/
private String printIndent(int num){
 String temp="";
 if(num>0){
  for(int i=0;i<num;i++){
   temp+=STANDARD_INDENT;
  }
 }
 return temp;
}
/**
* 设定行前的STANDARD_INDENT(一般指空格)
* @param indent STANDARD_INDENT的值
*/
public void setIndent(String indent){
 STANDARD_INDENT=indent;
}
/**
* 获得已经生成的xml字符串.在printDOMTree(Node node)方法后有效
* @return String
*/
public String getXmlResult(){
 return xmlString;
}
/**
* 设定最开始的深度级别(直接影响行前的STANDARD_INDENT(空格)数)
* @param level 级别数
*/
public void setBeginLevel(int level){
 indentLevel=level;
}
/**
* 设定xml文件的xml头
* @param header xml文件xml头。例如:<?xml version=/"1.0/" ?>
*/
public void setXmlHeader(String header){
  XmlHeader=header;
}
/**
* 设定换行符 默认为"/r/n"
* @param lineseparator 换行分割符,默认为"/r/n"
*/
public void setlineSeparator(String lineseparator){
  lineSeparator=lineseparator;
}
}


  XMLOutput.class 功能是用指定的string或InputStream生成文件(不一定是xml文件)。代码如下:

package com.ceic.workflow.xml 
import org.w3c.dom.*;
import java.io.*;
import java.util.*;
/**
 * Title:        有效XML 字符串生成xml文件的工具
 * Description:  有效XML 字符串生成xml文件的工具
 * Copyright:    Copyright (c) 2003
 * Company:      国电信息中心
 * @author 张治中
 * @version 1.0
 */
public class XmlOutput{
private String objectpath;
private String encoding="UTF8";
  public XmlOutput(){

  }
  /**
   * 构造器
   * @param filepath 生成的目标xml文件位置.
   */
  public XmlOutput(String filepath){
    objectpath=filepath;
  }
  /**
   * 设定生成的目标xml文件的位置
   * @param filepath 生成的目标xml文件位置.
   */
  public void setObjectPath(String filepath){
    objectpath=filepath;
  }
  /**
   * 设定生成xml文件的编码格式
   * @param encod 生成xml文件的编码格式,默认为 UTF8
   */
  public void setEncoding(String encod){
    encoding=encod;
  }
  /**
   * 根据指定的xmlstring生成xml文件.
   * @param xmlstring 指定的xml字符串
   */
  public void Output(String xmlstring){
    if(!checkObject()) {
      System.out.println("没有指定要写入的文件");
      return;
    }
    try{
//      StringBufferInputStream in=new 
//      StringBufferInputStream(xmlstring);
      FileOutputStream out=new FileOutputStream
       (new File(objectpath));
      java.io.Writer write=new java.io.
       OutputStreamWriter(out,encoding);
      write.write(xmlstring);
      write.close() 
    }catch(Exception ee){
      System.out.println(ee.getMessage());
      System.out.println("写文件出错");
    }
  }
  /**
   * 根据指定的输入流生成xml文件.
   * @param in 指定的InputStream
   */
  public void Output(InputStream in){
    if(!checkObject()) {
       System.out.println("没有指定要写入的文件");
       return;
    }
    try{
      StringBuffer temp=new StringBuffer();
      byte[] tempbyte=new byte[1024];
      while(in.read(tempbyte)!=-1){
        temp.append(new String(temp));
      }
      in.close() 
      String result=temp.toString() 
      FileOutputStream out=new FileOutputStream
       (new File(objectpath));
      java.io.Writer write=new java.io.OutputStreamWriter
       (out,encoding);
      write.write(result);
      write.close() 
     }catch(Exception eee){
      System.out.println(eee.getMessage());
      System.out.println("写文件出错");
    }


  }
  /**
   * 检查文件path是否为空
   * @return boolean
   */
  private boolean checkObject(){
    if(objectpath!=null&&objectpath.length() >0) return true;
    return false;
  }
}




  有了这些xml的操作工具后,下一步就是接着来进行实际的应用。在我以前的项目中(二次开发的),有个遗留问题就是tree型权限和 tree型角色的交互(包括各自的维护)。当时在表现层是用的 jsp+applet实现哪个tree图(给applet传入一个xml格式的文件流)。文件格式如下:

<node icon="/zdtadmin/images/Cluster_folder.gif" label=
 "退出登陆" target="_top" url="/zdtadmin/login.jsp">
</node>
<node icon="/zdtadmin/images/Cluster_folder.gif" label=
 "角色维护" target="mainFrame" url="/zdtadmin/default.jsp">
 <node icon="/zdtadmin/images/Cluster_folder.gif" label=
 "添加角色" target="mainFrame" url="/zdtadmin/peradmin
 /role_edit.jsp">
</node>
<node icon="/zdtadmin/images/Cluster_folder.gif" label=
"角色<->栏目" target="mainFrame" url="/zdtadmin/peradmin
/role_tree.jsp">
</node>
<node icon="/zdtadmin/images/Cluster_folder.gif" label=
"角色<->用户" target="mainFrame" url="/zdtadmin/peradmin
/role_user.jsp">
</node>
</node>


  其实就是一个比较规范的xml文档,在tree结构只有两层时比较容易就可以用jsp来out.println()出来。但是当结构边复杂时用jsp就不够了。在加上有权限在里面,问题就更复杂化了。在了解到了xml后及做了上面的一些工作后.决定用xml(通过递归方法生成tree 型结构的xml)来实现。代码如下:

package com.ceic.tree;
import java.io.*;
import org.w3c.dom.*;
import java.util.*;
import com.ceic.workflow.xml.*;
import com.ceic.publicSource.*;
import com.ceic.ResultSets.*;

public class CreateTree {
  private boolean Start=false;
  private Result rs;
  private XMLTool tool;
  private document.nbspdoc;
  private int BeginLevel=0;
  private String indent=" ";
  private String end="/r";
  private String header="<?xml version=/"1.0/" ?>";
  private String ParentTreeId="tree_id_p";
  private String TreeId="tree_id";
  private String defaultparent="0";
  private String NodeName="node";
  private int maxAttrs=20;
  private int maxsize=20;
  public int[] vec;
  private int mark=0;
  private String checkOne="label";
  private String[] nodeAttrList;
  private String colFlag="#";
  private String[] nodeAttrvalueList;
  private String defaultFlag="@";
  private Hashtable mapping=new Hashtable();
  private Vector collist=new Vector();
  private String rootName="zzz_test";
  private boolean EnableMakeUp=false;
  public CreateTree(){
    try{
    rs=ResultFactory.getResult("Vector");
    rs.setConnType("jdbc");
    String sql="select * from cm_tree";
    rs.setSql(sql);
    rs.Create() 
    }catch(Exception exec){
      System.out.println("初始化无效,请通过setResult()设定数据源");
    }
    tool=XMLToolFactory.getXMLTool() 
    doc=tool.Createdocument.) 
    tool.setdocument.ource(doc);
    init();
  }
  public void setParentTreeId(String parenttreeid){
    if(parenttreeid!=null&&parenttreeid.length() >0)  
    ParentTreeId=parenttreeid;
  }
  public void setTreeId(String treeid){
    if(treeid!=null&&treeid.length() >0) TreeId=treeid;
  }
  public void setDefaultParent(String defaultp){
    if(defaultp!=null&&defaultp.length() >0)
        defaultparent=defaultp;
  }
  public void setMaxTreeLevel(int MaxSize){
    if(MaxSize>0){
      maxsize=MaxSize;
      vec=null;
      vec=new int[maxsize];
      vec[0]=0;
    }
  }
  public void setCheckOne(String CheckOne){
    if(CheckOne!=null&&CheckOne.length() >0){
      checkOne=CheckOne;
    }
  }
  public void setHeader(String Header){
   try{
   if(Header!=null&&Header.length() >0){
     header=Header;
     tool.setHeader(header);
   }
   }catch(Exception e){
     System.out.println("XMLTool不存在");
   }
  }
  public void setdocument.document.nbspdocs){
    if(docs!=null){
      doc=docs;
      tool.setdocument.ource(doc);
    }
  }
  public void setXMLTool(XMLTool tools){
    if(tools!=null){
      tool=tools;
      doc=tool.Createdocument.) 
      tool.setdocument.ource(doc);

    }
  }
  public void setResult(Result tools){
    if(tools!=null){
      close() 
      rs=tools;
    }
  }
  public void setmaxAttrs(int max){
    if(max>0) maxAttrs=max;
  }
  public void setAttrList(String[] list){
    if(list.length >0){
      if(list.length >maxAttrs) maxAttrs=list.length 
          nodeAttrList=null;
          nodeAttrList=new String[maxAttrs];
          nodeAttrvalueList=null;
          nodeAttrvalueList=new String[maxAttrs];
          collist.clear() 
          for(int i=0;i<list.length i++){
            nodeAttrList[i]=list[i];
            collist.addElement(nodeAttrList[i]);
          }
    }
  }
  public void setvalueList(String[] list){
      if(list.length >0){
        if(list.length >maxAttrs) maxAttrs=list.length 
            nodeAttrvalueList=null;
            nodeAttrvalueList=new String[maxAttrs];
            mapping.clear() 
            for(int i=0;i<collist.size();i++){
              nodeAttrvalueList[i]=list[i];
              mapping.put(collist.elementAt(i).toString(),
	      nodeAttrvalueList[i]);

            }
      }
  }
  public void addMapping(String name,String value){
   if(name!=null&&name.length() >0){
    collist.addElement(name);
    mapping.put(name,value);
    }
  }
  public void setColFlage(String colflag){
    if(colflag!=null&&colflag.length() >0){
      colFlag =colflag;
    }
  }
  public void setLineEnd(String lineend){
    if(lineend!=null&&lineend.length() >0){
      end=lineend;
    }
  }
  public void setTreeNodeName(String nodename){
    if(nodename!=null&&nodename.length() >0&&
    !nodename.equals(rootName)){
      NodeName=nodename;
    }
  }
  public document.nbspgetdocument.){
    return doc;
  }
  public XMLTool getXMLTool(){
    return tool;
  }
  public Result getResult(){
    return rs;
  }
  public void setDefaultFlag(String flag){
    if(flag!=null&&flag.length() >0){
      defaultFlag=flag;
    }
  }
  public CreateTree(Result rss,XMLTool xmltool){
    try{
    rs=rss;
    tool=xmltool;
    doc=tool.Createdocument.) 
    tool.setdocument.ource(doc);
    init();
    }catch(Exception eer){
      eer.printStackTrace() 
      System.out.println("初始化失败");
    }
  }
  private void  init(){
    try{

    vec=new int[maxsize];
    vec[0]=0;
    nodeAttrList=new String[maxAttrs];
    nodeAttrvalueList=new String[maxAttrs];
    nodeAttrList[0]="label";
    nodeAttrList[1]="icon";
    nodeAttrList[2]="url";
    nodeAttrList[3]="target";
    nodeAttrList[4]="parentid";
    nodeAttrList[5]="id";

    nodeAttrvalueList[0]=colFlag+"tree_name";
    nodeAttrvalueList[1]="/zdtadmin/images/Cluster_folder.gif";
    nodeAttrvalueList[2]=colFlag+"tree_address";
    nodeAttrvalueList[3]=colFlag+"tree_target"+
     defaultFlag+"_blank";
    nodeAttrvalueList[4]=colFlag+"tree_id_p";
    nodeAttrvalueList[5]=colFlag+"tree_id";
    for(int i=0;i<6;i++){
      collist.addElement(nodeAttrList[i]);
      mapping.put(nodeAttrList[i],nodeAttrvalueList[i]);
    }
    }catch(Exception eer){
      eer.printStackTrace() 
      System.out.println("初始化失败");
    }
  }
  public void CreateXML(){
    Element root=tool.CreateElement(rootName);
    doc.appendChild(root);
    tool.setMarkSign(NodeName);
    rs.first() 
    mark=0;
    Start=false;
    CreateMapTree(defaultparent,BeginLevel,root);
    //tool.isEnableMakeUp();

  }
  public void CreateXML(String selfroot,int indexs){
    Element root;
    if(selfroot==null||selfroot.length()==0){
    root=tool.CreateElement(rootName);
    doc.appendChild(root);
    }
    else{
      NodeList list=doc.getElementsByTagName(selfroot);
      if(list.getLength() >0){
      if(indexs>list.getLength()) indexs=0;
      else
        {
        if(indexs>=1) indexs=indexs-1;
        else indexs=0;
        }
      root=((Element)doc.getElementsByTagName(selfroot).
      item(indexs));
      //rootName=selfroot;
      }else{
        root=tool.CreateElement(rootName);
        doc.appendChild(root);
      }
    }
    tool.setMarkSign(NodeName);
    rs.first() 
    mark=0;
    Start=false;
    CreateMapTree(defaultparent,BeginLevel,root);
    //tool.isEnableMakeUp();

  }
  public void isEnableMakeUp(){
    EnableMakeUp=true;
    tool.isEnableMakeUp() 
  }
  public void isNotEnableMakeUp(){
    EnableMakeUp=false;
    tool.isNotEnableMakeUp() 
  }
  public void CreateXmlFile(String filepath){
    tool.Output(filepath,doc);
   }
   public void CreateXmlFile(String filepath,boolean noTop){
    tool.Output(filepath,doc,noTop);
   }
   public void CreateSelfXmlFile(String filepath,boolean noTop){
     tool.Output(filepath,doc.getElementsByTagName
     (rootName).item(0),noTop);
   }
   public void CreateXmlFile(String filepath,String nodeName,
   int indexs,boolean noTop){
     NodeList list=doc.getElementsByTagName(nodeName);
     if(list.getLength() >0){
     if(indexs>list.getLength()) indexs=0;
     else{
       if(indexs>=1) indexs=indexs-1;
       else indexs=0;
     }
     tool.Output(filepath,doc.getElementsByTagName(nodeName).
     item(indexs),noTop);
     }

   }
   public void setEncoding(String encod){
     tool.setEncoding(encod);
   }
  private void CreateMapTree(String type,int level,Node node){
    try{
    int templevel=level;
     do{

      if(rs.getString(ParentTreeId).equals(type)){
       if(!EnableMakeUp){
       Text tx=doc.createTextNode(end);
       node.appendChild(tx);
       CreateIndet(templevel,node);
        }
       String newtype=rs.getString(TreeId);
       Element ele=tool.CreateElement(NodeName);
       CreateTreeModel(ele,rs);

//       if(CheckNode(ele,checkOne)){

       node.appendChild(ele);
       templevel++;
       mark++;
       vec[mark]=0;
       rs.first() 
       CreateMapTree(newtype,templevel,ele);
//       }
     }
     vec[mark]++;
    }while(rs.next());
    mark--;
    move();
    }catch(Exception e){
      e.printStackTrace() 

      System.out.println("生成节点失败");
    }
  }
  private void CreateTreeModel(Node node,Result rstemp){
    try{
//    ((Element)node).setAttribute(LABEL,rstemp.getString
//    ("tree_name"));
//    ((Element)node).setAttribute(ICON,icon);
//    ((Element)node).setAttribute(URL,rstemp.getString
//      ("tree_address"));
//    if(rstemp.getString("tree_target")!=null&&rstemp.getString
//      ("tree_target").length() >0){
//      ((Element)node).setAttribute(TARGET,rstemp.
//       getString("tree_target"));
//    }
      String tempattr,tempvalue,tempcol,tempdefault,tempcolvalue;
      for(int i=0;i<collist.size();i++){
        tempcol="";
        tempdefault="";
        tempcolvalue="";
        tempattr=collist.elementAt(i).toString() 
        tempvalue=mapping.get(tempattr).toString() 
         if(tempattr!=null&&tempattr.length() >=0){
        if(tempvalue.indexOf(colFlag)>=0){
          String[] aaa=TheStrings.split(tempvalue,colFlag);
          String header="";
          String thevalue="";
          if(aaa.length >1){
            header=aaa[0];
            thevalue=aaa[1];
          }else{
            thevalue=aaa[0];
          }

          String[] temps=TheStrings.split(thevalue,defaultFlag);
          if(temps.length >1) tempdefault=temps[1];
          tempcol=temps[0];
          tempcolvalue=rstemp.getString(tempcol);

          if(tempdefault.length() >0){
            if(tempcolvalue.length() >0){
              ((Element)node).setAttribute(tempattr,
	       header+tempcolvalue);
            }else{
              ((Element)node).setAttribute(tempattr,tempdefault);
            }
           }else{
             ((Element)node).setAttribute(tempattr,
	     header+tempcolvalue);
           }
         }else{
          ((Element)node).setAttribute(tempattr,tempvalue);
           }
        }
      }
    }catch(Exception ee){
      ee.printStackTrace() 
      System.out.println("建立数据失败");
    }
  }
  public void deleteNode(String nodename){
    tool.delNode(NodeName,nodename,true);
  }
  private void CreateIndet(int level,Node node){

    for(int i=0;i<level;i++){
      Text tx=doc.createTextNode(indent);
      node.appendChild(tx);
    }

  }
  private void move(){
    if(mark>=0){

    rs.first() 

    for(int i=0;i<vec[mark];i++){

        rs.next() 
    }

    }

  }
public void close(){
  rs.close() 

}
private boolean CheckNode(Node node,String oneType){
String label=((Element)node).getAttribute(oneType);
if(tool.setMark(oneType,label)){
  return false;
}
  return true;

}
public String getXmlString(boolean noTop){
  XmlBuilder builder=new XmlBuilder();
  builder.printDOMTree(doc,noTop);
  return builder.getXmlResult() 
}
public String getSelfXmlString(boolean noTop){
  XmlBuilder builder=new XmlBuilder();
  Node node=doc.getElementsByTagName(rootName).item(0);
  builder.printDOMTree(node,noTop);
  return builder.getXmlResult() 
}
public Vector getParents(String id){
  Vector vec=new Vector();
  getParent(id,vec);
  return vec;
}

private void getParent(String id,Vector vec){
  tool.setMarkSign(NodeName);
  tool.setMark(checkOne,id);
  Node node=doc.getElementsByTagName(NodeName).item
   (tool.getIndex());
  if(node.getParentNode() !=null){
  String tempid=((Element)node.getParentNode()).
   getAttribute(checkOne);
  if(tempid!=null&&tempid.length() >0){
    if(tempid.equals(defaultparent)){
      vec.addElement(defaultparent);
      return;
    }else{
      vec.addElement(tempid);
      getParent(tempid,vec);
    }
   }
  }
}
public Vector getSons(String id){
  Vector vec=new Vector();
  getSon(id,vec);
  return vec;
}
private void getSon(String id,Vector vec){
  tool.setMarkSign(NodeName);
  tool.setMark(checkOne ,id);
  Node node=doc.getElementsByTagName(NodeName).
   item(tool.getIndex());
  NodeList list= node.getChildNodes() 
  if(list.getLength() >0){
   String tempid;
    for(int i=0;i<list.getLength() i++){
      if(list.item(i).getNodeType()==Node.ELEMENT_NODE){
      tempid=((Element)list.item(i)).getAttribute(checkOne);
      if(tempid!=null&&tempid.length() >0){
         vec.addElement(tempid);
         getSon(tempid,vec);
       }
      }
   }
  }
}

//
//public static void main(String[] a){
//  String[] name={"icon","label","url","target","id","parentid"};
//String[] value={"/zdtadmin/images/Cluster_folder.gif",
//"#tree_name","#tree_address","#tree_target@mainFrame",
//"#tree_id","#tree_id_p"};
//CreateTree create=new CreateTree();
//XMLTool tool=XMLToolFactory.getXMLTool() 
//Result rs=ResultFactory.getResult("Vector");
//rs.setConnType("jdbc");
//rs.setSql("select * from cm_tree where tree_id in(3,44,1,32,29)
//and tree_enable='1' order by tree_id");
//rs.Create() 
//create.setResult(rs);
//create.setXMLTool(tool);
//create.isEnableMakeUp() 
//create.setAttrList(name);
//create.setvalueList(value);
//create.setCheckOne("id");
//create.setDefaultParent("0");
//create.setTreeId("tree_id");
//create.setParentTreeId("tree_id_p");
//create.setTreeNodeName("node");
//create.setEncoding("GBK");
//create.CreateXML();
//Vector vec=create.getParents("30");
//for(int i=0;i<vec.size() i++){
//  System.out.println(vec.elementAt(i));
//}
//create.deleteNode("id");
//create.deleteNode("parentid");
//create.CreateSelfXmlFile("d:/tomcat/webapps/test_self.xml",true);
//create.close() 
//
//
//
//}

}


  main()是 实例。private Result rs;是自定义记录集容器( Vector装所有记录,Vector中对象hashTable,hashTable中为字段名和字段值,还有一个字段名列表Vector,可能有什么安全隐患,因为我自己对Vector,hashTable不是很了解,希望高手指点).通过这种xml的解决方法,就很好解决了tree图显示,并解决了 tree结构中的结构编辑(主要好处是保证tree结构的完整性,例如父节点休眠,所有子节点也休眠,激活子节点必须保证父节点已经被激活。),如果没有 xml文档结构,这些操作将是很复杂的递归算法,并且会频繁的操作数据库。

  最后一个例子:数据库数据和xml文件同步。

  代码如下:

package com.ceic.tree;
import com.ceic.ConnPool.*;
import com.ceic.ResultSets.*;
import com.ceic.publicSource.*;
import java.util.*;
import com.ceic.workflow.xml.*;
import org.w3c.dom.*;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: </p>
 * @author unascribed
 * @version 1.0
 */

public class TableToXml {
  private boolean Start=false;
  private Result rs;
  private XMLTool tool;
  private document.nbspdoc;
  private int BeginLevel=0;
  private String indent=" ";
  private String end="/r";
  private String header="<?xml version=/"1.0/" ?>";
  private int maxAttrs=20;
  private int mark=0;
  private String checkOne="label";
  private String[] nodeAttrList;
  private String colFlag="#";
  private String[] nodeAttrvalueList;
  private String defaultFlag="@";
  private Hashtable mapping=new Hashtable();
  private Vector collist=new Vector();
  private String rootName="table";
  private String NodeName="col";
  private boolean EnableMakeUp=false;
  private int tempindex=0;
  private void  init(){
    try{
    nodeAttrList=new String[maxAttrs];
    nodeAttrvalueList=new String[maxAttrs];
    nodeAttrList[0]="label";
    nodeAttrList[1]="icon";
    nodeAttrList[2]="url";
    nodeAttrList[3]="target";
    nodeAttrList[4]="parentid";
    nodeAttrList[5]="id";

    nodeAttrvalueList[0]=colFlag+"tree_name";
    nodeAttrvalueList[1]="/zdtadmin/images/Cluster_folder.gif";
    nodeAttrvalueList[2]=colFlag+"tree_address";
    nodeAttrvalueList[3]=colFlag+"tree_target"+
      defaultFlag+"_blank";
    nodeAttrvalueList[4]=colFlag+"tree_id_p";
    nodeAttrvalueList[5]=colFlag+"tree_id";
    for(int i=0;i<6;i++){
      collist.addElement(nodeAttrList[i]);
      mapping.put(nodeAttrList[i],nodeAttrvalueList[i]);
    }
    }catch(Exception eer){
      eer.printStackTrace() 
      System.out.println("初始化失败");
    }
  }
  public TableToXml() {
    tool=XMLToolFactory.getXMLTool() 
    doc=tool.Createdocument.) 
    tool.setdocument.ource(doc);
    init();
  }
  public TableToXml(Result rs) {
    setResult(rs);
    tool=XMLToolFactory.getXMLTool() 
    doc=tool.Createdocument.) 
    tool.setdocument.ource(doc);
    init();
  }
  public TableToXml(Result rs,XMLTool toolss) {
    setResult(rs);
    setXMLTool(toolss);
    init();
  }
  public void setCheckOne(String CheckOne){
    if(CheckOne!=null&&CheckOne.length() >0){
      checkOne=CheckOne;
    }
  }
  public void setHeader(String Header){
    try{
    if(Header!=null&&Header.length() >0){
      header=Header;
      tool.setHeader(header);
    }
    }catch(Exception e){
      System.out.println("XMLTool不存在");
    }
  }
  public void setdocument.document.nbspdocs){
    if(docs!=null){
      doc=docs;
      tool.setdocument.ource(doc);
    }
  }
  public void setXMLTool(XMLTool tools){
    if(tools!=null){
      tool=tools;
      doc=tool.Createdocument.) 
      tool.setdocument.ource(doc);

    }
  }
  public void setResult(Result tools){
    if(tools!=null){
      close() 
      rs=tools;
    }
  }
  public void setmaxAttrs(int max){
    if(max>0) maxAttrs=max;
  }
  public void setAttrList(String[] list){
    if(list.length >0){
      if(list.length >maxAttrs) maxAttrs=list.length 
          nodeAttrList=null;
          nodeAttrList=new String[maxAttrs];
          nodeAttrvalueList=null;
          nodeAttrvalueList=new String[maxAttrs];
          collist.clear() 
          for(int i=0;i<list.length i++){
            nodeAttrList[i]=list[i];
            collist.addElement(nodeAttrList[i]);
          }
    }
  }
  public void setvalueList(String[] list){
      if(list.length >0){
        if(list.length >maxAttrs) maxAttrs=list.length 
            nodeAttrvalueList=null;
            nodeAttrvalueList=new String[maxAttrs];
            mapping.clear() 
            for(int i=0;i<collist.size();i++){
              nodeAttrvalueList[i]=list[i];
              mapping.put(collist.elementAt(i).toString(),n
	      odeAttrvalueList[i]);

            }
      }
  }
  public void addMapping(String name,String value){
   if(name!=null&&name.length() >0){
    collist.addElement(name);
    mapping.put(name,value);
    }
  }
  public void setColFlage(String colflag){
    if(colflag!=null&&colflag.length() >0){
      colFlag =colflag;
    }
  }
  public void setLineEnd(String lineend){
    if(lineend!=null&&lineend.length() >0){
      end=lineend;
    }
  }
  public void setTreeNodeName(String nodename){
    if(nodename!=null&&nodename.length() >0&&!nodename.
    equals(rootName)){
      NodeName=nodename;
    }
  }
  public document.nbspgetdocument.){
    return doc;
  }
  public XMLTool getXMLTool(){
    return tool;
  }
  public Result getResult(){
    return rs;
  }
  public void setDefaultFlag(String flag){
    if(flag!=null&&flag.length() >0){
      defaultFlag=flag;
    }
  }
  public void isEnableMakeUp(){
    EnableMakeUp=true;
    tool.isEnableMakeUp() 
  }
  public void isNotEnableMakeUp(){
    EnableMakeUp=false;
    tool.isNotEnableMakeUp() 
  }

  public void CreateXmlFile(String filepath){
    tool.Output(filepath,doc);
   }
   public void CreateXmlFile(String filepath,boolean noTop){
    tool.Output(filepath,doc,noTop);
   }
   public void CreateSelfXmlFile(String filepath,boolean noTop){
     tool.Output(filepath,doc.getElementsByTagName(rootName).
     item(0),noTop);
   }
   public void CreateXmlFile(String filepath,String nodeName,
   int indexs,boolean noTop){
     NodeList list=doc.getElementsByTagName(nodeName);
     if(list.getLength() >0){
     if(indexs>list.getLength()) indexs=0;
     else{
       if(indexs>=1) indexs=indexs-1;
       else indexs=0;
     }
     tool.Output(filepath,doc.getElementsByTagName(nodeName).
      item(indexs),noTop);
     }

   }
   public void setEncoding(String encod){
     tool.setEncoding(encod);
   }
   public void setRootAttr(String name,String value){
     try{
     if(name!=null&&name.length() >0)     
     ((Element)doc.getElementsByTagName(rootName).item(tempindex)).
       setAttribute(name,value);
     }catch(Exception e){
       System.out.println("还没有建立document.
       象或root element对象"+e.getMessage());
     }
   }
   public void CreateXML(boolean colListAuto,boolean checkone){
    Element root=tool.CreateElement(rootName);
    doc.appendChild(root);
    tool.setMarkSign(NodeName);
    rs.first() 
    if(colListAuto){
     Vector vec=(Vector)rs.getMetaData() 
     if(vec.size() >this.maxAttrs ) {
       maxAttrs=vec.size() 
       nodeAttrList=null;
       nodeAttrvalueList=null;
       nodeAttrList=new String[maxAttrs];
       nodeAttrvalueList=new String[maxAttrs];
     }
     if(collist!=null) {collist.removeAllElements() collist.
      clear() }
     if(mapping!=null) {mapping .clear() }
     for(int k=0;k<vec.size() k++){
       nodeAttrList[k]=vec.elementAt(k).toString() 
       nodeAttrvalueList[k]=colFlag+nodeAttrList[k];
       collist.addElement(nodeAttrList[k]);
       mapping.put(nodeAttrList[k],nodeAttrvalueList[k]);
     }
    }
    mark=0;
    Start=false;
    CreateMapTree(BeginLevel,root,checkone);
    //tool.isEnableMakeUp();

  }
  public void CreateXML(String selfroot,int indexs,boolean 
   colListAuto,boolean checkone){
    Element root;
    if(selfroot==null||selfroot.length()==0){
    root=tool.CreateElement(rootName);
    doc.appendChild(root);
    }
    else{
      NodeList list=doc.getElementsByTagName(selfroot);
      if(list.getLength() >0){
      if(indexs>list.getLength()) indexs=0;
      else
        {
        if(indexs>=1) indexs=indexs-1;
        else indexs=0;
        }
      root=((Element)doc.getElementsByTagName(selfroot)
       .item(indexs));
      rootName=selfroot;
      tempindex=indexs;
      }else{
        root=tool.CreateElement(rootName);
        doc.appendChild(root);
      }
    }
    tool.setMarkSign(NodeName);
    rs.first() 
    if(colListAuto){
     Vector vec=(Vector)rs.getMetaData() 
     if(vec.size() >this.maxAttrs ) {
       maxAttrs=vec.size() 
       nodeAttrList=null;
       nodeAttrvalueList=null;
       nodeAttrList=new String[maxAttrs];
       nodeAttrvalueList=new String[maxAttrs];
     }
     if(collist!=null) {collist.removeAllElements() 
      collist .clear() }
     if(mapping!=null) {mapping .clear() }
     for(int k=0;k<vec.size() k++){
       nodeAttrList[k]=vec.elementAt(k).toString() 
       nodeAttrvalueList[k]=colFlag+nodeAttrList[k];
       collist.addElement(nodeAttrList[k]);
       mapping.put(nodeAttrList[k],nodeAttrvalueList[k]);
     }
    }
    mark=0;
    Start=false;
    CreateMapTree(BeginLevel,root,checkone);
    //tool.isEnableMakeUp();

  }
  private void CreateMapTree(int level,Node node,boolean checkone){
    try{
    int templevel=level;
    do{
      Element ele=tool.CreateElement(NodeName ) 
      CreateTreeModel(ele,rs);
      if(CheckNode(ele,checkOne)){
        if(!EnableMakeUp){
        Text tx=doc.createTextNode(end);
        node.appendChild(tx);
        CreateIndet(templevel,node);
        }
        node.appendChild(ele);
      }
    }while(rs.next() );
    }catch(Exception e){
      e.printStackTrace() 

      System.out.println("生成节点失败");
    }
  }

  private void CreateTreeModel(Node node,Result rstemp){
    try{
//    ((Element)node).setAttribute(LABEL,rstemp.getString
//     ("tree_name"));
//    ((Element)node).setAttribute(ICON,icon);
//    ((Element)node).setAttribute(URL,rstemp.getString
//     ("tree_address"));
//    if(rstemp.getString("tree_target")!=null&&rstemp.getString
//      ("tree_target").length() >0){
//      ((Element)node).setAttribute(TARGET,rstemp.getString
//       ("tree_target"));
//    }
      String tempattr,tempvalue,tempcol,tempdefault,tempcolvalue;
      for(int i=0;i<collist.size();i++){
        tempcol="";
        tempdefault="";
        tempcolvalue="";
        tempattr=collist.elementAt(i).toString() 
        tempvalue=mapping.get(tempattr).toString() 
         if(tempattr!=null&&tempattr.length() >=0){
        if(tempvalue.indexOf(colFlag)>=0){
          String[] aaa=TheStrings.split(tempvalue,colFlag);
          String header="";
          String thevalue="";
          if(aaa.length >1){
            header=aaa[0];
            thevalue=aaa[1];
          }else{
            thevalue=aaa[0];
          }

          String[] temps=TheStrings.split(thevalue,defaultFlag);
          if(temps.length >1) tempdefault=temps[1];
          tempcol=temps[0];
          tempcolvalue=rstemp.getString(tempcol);

          if(tempdefault.length() >0){
            if(tempcolvalue.length() >0){
              ((Element)node).setAttribute(tempattr,
	      header+tempcolvalue);
            }else{
              ((Element)node).setAttribute(tempattr,tempdefault);
            }
           }else{
             ((Element)node).setAttribute(tempattr,
	     header+tempcolvalue);
           }
         }else{
          ((Element)node).setAttribute(tempattr,tempvalue);
           }
        }
      }
    }catch(Exception ee){
      ee.printStackTrace() 
      System.out.println("建立数据失败,可能的原因是指定的节点值
      的列表中的元素中用到了不能获取的字段。");
    }
  }
  public void deleteNode(String nodename){
    tool.delNode(NodeName,nodename,true);
  }
  private void CreateIndet(int level,Node node){

    for(int i=0;i<level;i++){
      Text tx=doc.createTextNode(indent);
      node.appendChild(tx);
    }

  }
public void close(){
if(rs!=null)  rs.close() 

}
private boolean CheckNode(Node node,String oneType){
String label=((Element)node).getAttribute(oneType);
if(tool.setMark(oneType,label)){
  return false;
}
  return true;

}
public String getXmlString(boolean noTop){
  XmlBuilder builder=new XmlBuilder();
  builder.printDOMTree(doc,noTop);
  return builder.getXmlResult() 
}

public static void main(String args[]){
  String[] name={"label","url","target","id","parentid"};
  String[] value={"#tree_name","#tree_address@/zdtadmin/default.jsp",
  "#tree_target@_blank","#tree_id","#tree_id_p"};
  //#开头表示读取指定的字段名的值,@后面跟的是#字段名读取没有值或为null时
  //的默认值,可以做简单的组合。比如: "login.jsp?id=#tree_name@1001"
  Result rs=ResultFactory.getResult("Vector");
  rs.setConnType("jdbc");
  rs.setSql("select * from cm_tree where tree_enable='1'");
  rs.Create() 
  TableToXml ttx=new TableToXml(rs);
  ttx.setAttrList(name);
  ttx.setvalueList(value);
//  ttx.setEncoding("GBK");
  ttx.setHeader("<?xml version=/"1.0/" ?>");
  ttx.CreateXML(false,false);
  //第一个参数是是否用sql中全部的字段,否则用指定的字段和值的列表。
  //第2个参数指是否检查唯一性。通过ttx.setCheckOne(String str)
  //设定唯一字段.
  ttx.setRootAttr("name","cm_tree");
  ttx.CreateXmlFile("d://xmltest//example//ttx2.xml");
  ttx.close() 
  System.out.println(ttx.getXmlString(true));
}
}


  其中的Result同上。不过生成的xml中把字段名都当作attribute来处理(不想太复杂)。

  以上是我在接触xml后对xml的理解和实践。用的是最笨的方法(手工操作xml),写出来就是希望能从高手的意见中学到东西。如果有机会,我下一次会把xml和xslt结合的实践例子拿出来和大家一起研究。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值