学习java&xml心得(二)

   XMLToolTest.class实现了对xml文档的操作。包括建立一个新xml document.档结构及内容或从指定xml文件或的document.构和内容,output到指定的xml文件(或更新xml文件),获取和设定指定节点名的指定属性(或属性列表),在指定节点添加子节点、删除子节点、编辑子节点(先删除在添加,待完善),支持在文档中定位(下标定位,和查询定位,如:定位到test节点的 name attribute的value="张治中"的节点,有简单的复合查询定位,暂时是全and的关系. :) ),定位后可以和全面的操作联合使用(有点数据库的影子,和自己想做的应用有关)。后来又根据它做了一个数据库和xml对导的例子。代码如下:

       
       
        
        package com.ceic.workflow.xml.Tool;
import com.ceic.workflow.xml.*;
import org.w3c.dom.*;
/**
 * Title:        XML处理工具的 运算和实现部分的接口
 * Description:  XML处理工具的 运算和实现部分的接口
 * Copyright:    Copyright (c) 2003
 * Company:      国电信息中心
 * @author 张治中
 * @version 1.0
 * XML处理工具的 运算和实现部分 的接口
 * XMLTool的实现子类,其中的XML解析器从XMLParserFactory中获得.
 * 没有说明的方法和参数参见XMLTool接口.
 */
public class XMLToolTest implements XMLTool
{

  private  XMLParser parser;
  private  String ParserType=
   XMLParserFactory.getDefaultType();
  private  String ParserClassName="";
  private  int Index=0;
  private  String markName="";
  private  document.nbspdoc;
  private  int DefaultBegin=0;
  private String encoding="UTF8";
  private String filepath="";
  private boolean EnableMakeUp=false;
  private String header="<?xml version=/"1.0/" ?>";
   public XMLToolTest()
   {

   }
   public Object Build(String path, boolean vali)
   {
     if(path!=null&&path.length() >0){
       parser=XMLParserFactory.getXMLParser
        (ParserType,ParserClassName);
       if(parser!=null){
        doc=(document.parser.parse(path,vali);
        filepath=path;
        return doc;
       }
     }
   return null;
   }
   public Object Build(String xmlString)
   {
     if(xmlString!=null&&xmlString.length() >0){
       parser=XMLParserFactory.getXMLParser
        (ParserType,ParserClassName);
       if(parser!=null){
        doc=(document.parser.parseString(xmlString);
        filepath="";
        return doc;
       }
     }
   return null;
   }
   public void setdocument.ource(document.nbspdocs){
     doc=docs;
   }

   public void setParser(String ParserName, String ClassName)
   {
    if(ParserName!=null&&ParserName.length() >0){
      ParserType=ParserName;
      ParserClassName=ClassName;
    }
   }

   public void setProperty(String NodeName,String 
    propertyName,String value,boolean setall){
     try{
       NodeList list=doc.getElementsByTagName(NodeName);
       if(list.getLength() >0&&value!=null&&value.length()>0)
         {
         if(setall){
           for(int i=0;i<list.getLength() i++){

             if(propertyName!=null&&propertyName.length()>0)
	     {

                ((Element)list.item(i)).setAttribute
		(propertyName,value);
             }
           else{
                list.item(i).setNodevalue(value);
           }
          }

         }else{

         if(propertyName!=null&&propertyName.length()>0){
           if(NodeName.equals(markName)){
                ((Element)list.item(Index)).setAttribute
		(propertyName,value);
             }
          else{
               ((Element)list.item(DefaultBegin)).
	        setAttribute(propertyName,value);
          }
        }else{

          if(NodeName.equals(markName)){
               list.item(Index).setNodevalue(value);
            }
         else{
              list.item(DefaultBegin).setNodevalue(value);
          }

        }
       }
     }
     }catch(Exception ee){
       System.out.println("设定"+NodeName+"节点的"+
       propertyName+"属性出错");
     }
   }

   public String getProperty(String NodeName, 
     String propertyName)
   {
     try{
     NodeList list=doc.getElementsByTagName(NodeName);
     if(list.getLength() >0){
      if(propertyName!=null&&propertyName.length() >0){
       if(NodeName.equals(markName)){
         return ((Element)list.item(Index)).getAttribute
	  (propertyName);
       }else{
         return ((Element)list.item(DefaultBegin)).
	  getAttribute(propertyName);
       }
      }else{
       if(NodeName.equals(markName)){
         return ((Element)list.item(Index)).getNodevalue() 
       }else{
         return ((Element)list.item(DefaultBegin)).
	  getNodevalue() 
       }
      }
     }
     return null;
     }catch(Exception ee){
       System.out.println("getProperty("+NodeName+","+
        propertyName+");出错"+ee.getMessage());
       return null;
     }
  }
  public String[] getPropertys(String NodeName, 
    String propertyName)
   {
     try{
       String[] temp;
       NodeList list=doc.getElementsByTagName(NodeName);
       if(list.getLength() >0){
         if(propertyName!=null&&propertyName.length() >0){
           temp=new String[list.getLength()];
           for(int i=0;i<list.getLength() i++){
             temp[i]=((Element)list.item(i)).
	      getAttribute(propertyName);
           }
           return temp;
         }else{
           temp=new String[list.getLength()];
           for(int i=0;i<list.getLength() i++){
             temp[i]=((Element)list.item(i)).getNodevalue() 
           }
           return temp;
         }
       }
       return null;
     }catch(Exception ee){
       System.out.println("getPropertys("+NodeName+","+
        propertyName+");出错");
       return null;
     }
  }

  public String getParent(String returnAttr){
    String tempreturn="";
    String tempnode=markName 
    int tempindex=Index 
    NodeList list=doc.getElementsByTagName(markName);
    Node node=list.item(Index);
    if(returnAttr!=null&&returnAttr.length() >0){
      tempreturn=((Element)node.getParentNode()).
       getAttribute(returnAttr);
    }else{
      tempreturn=node.getParentNode().getNodevalue() 
    }
    return tempreturn;
   }


   public void setFormat(String XMLToolName, 
     String classname){}

   public void addNode(String parent, Node NodeName,
     boolean addall)
   {
     try{
     NodeList list=doc.getElementsByTagName(parent);

      if(list.getLength() >0){
        if(addall){
          for(int i=0;i<list.getLength() i++){
            int type=NodeName.getNodeType() 
            switch(type){
              case Node.ATTRIBUTE_NODE: {
                ((Element)list.item(i)).setAttribute(((Attr)
          NodeName).getName() ,((Attr)NodeName).getvalue());
              }
              default:{
                list.item(i).appendChild(NodeName);
              }
           }
          }
        }else{
            if(parent.equals(markName)){
              int type=NodeName.getNodeType() 
            switch(type){
              case Node.ATTRIBUTE_NODE: {
                ((Element)list.item(Index)).setAttribute
(((Attr)NodeName).getName() ,((Attr)NodeName).getvalue());
              }
              default:{
                list.item(Index).appendChild(NodeName);
              }
           }
            }else{

              int type=NodeName.getNodeType() 
            switch(type){
              case Node.ATTRIBUTE_NODE: {
                ((Element)list.item(DefaultBegin)).
 setAttribute(((Attr)NodeName).getName() ,
 ((Attr)NodeName).getvalue());
              }
              default:{
              list.item(DefaultBegin).appendChild(NodeName);
              }
           }

            }
         }

      }
     }catch(Exception e){
       System.out.println("增加节点出错");
     }
   }


   public void delNode(String parent,String NodeName,
     boolean delall)
   {
     try{
     NodeList list=doc.getElementsByTagName(parent);
       if(list.getLength() >0){
        if(delall){
          for(int i=0;i<list.getLength() i++){
            try{
            ((Element)list.item(i)).removeAttribute(NodeName);
            }catch(Exception ee){}

            NodeList tlist=list.item(i).getChildNodes() 
            if(tlist.getLength() >0){
             for(int k=0;k<tlist.getLength() k++){
               if(NodeName.equals(tlist.item(k).getNodeName())){
                short type=tlist.item(k).getNodeType() 
                if(type==Node.ATTRIBUTE_NODE){
                  ((Element)list.item(i)).removeAttribute
		  (NodeName);
                }
                else list.item(i).removeChild(tlist.item(k));
                break;
               }
             }
           }

          }
        }else{
            if(parent.equals(markName)){
              try{
            ((Element)list.item(Index)).removeAttribute(NodeName);
            }catch(Exception ee){}

              NodeList tlist=list.item(Index).getChildNodes() 
                   if(tlist.getLength() >0){
                     for(int k=0;k<tlist.getLength() k++){
                       if(NodeName.equals(tlist.item(k).
		         getNodeName())){
                         short type=tlist.item(Index).getNodeType() 
                         if(type==Node.ATTRIBUTE_NODE){
                           ((Element)list.item(Index)).
			   removeAttribute(NodeName);
                         }
                         else list.item(Index).removeChild
			 (tlist.item(k));
                         break;
                       }
                     }
           }
            }else{
              try{
            ((Element)list.item(DefaultBegin)).removeAttribute
	     (NodeName);
            }catch(Exception ee){}

              NodeList tlist=list.item(DefaultBegin).
	       getChildNodes() 
                   if(tlist.getLength() >0){
                     for(int k=0;k<tlist.getLength() k++){
                       if(NodeName.equals(tlist.item(k).
		        getNodeName())){
                         short type=tlist.item(Index).
			 getNodeType() 
                         if(type==Node.ATTRIBUTE_NODE){
                           ((Element)list.item(DefaultBegin)).
			   removeAttribute(NodeName);
                         }
                         else list.item(DefaultBegin).
			 removeChild(tlist.item(k));
                         break;
                       }
                     }
            }

            }
        }
      }
     }catch(Exception e){
       System.out.println("删除节点出错");
     }
   }

   public void editNode(String parent,String NodeOld,
    Node NodeNew,boolean editAll)
   {
     try{
     NodeList list=doc.getElementsByTagName(parent);

      if(list.getLength() >0){
        if(editAll){
          for(int i=0;i<list.getLength() i++){
           NodeList tlist=list.item(i).getChildNodes() 
           if(tlist.getLength() >0){
            for(int k=0;k<tlist.getLength() k++){
              if(NodeOld.equals(tlist.item(k).getNodeName())){
               list.item(i).replaceChild(tlist.item(k),NodeNew);
               break;
              }
            }
           }
          }
        }else{
            if(parent.equals(markName)){
              NodeList tlist=list.item(Index).getChildNodes() 
           if(tlist.getLength() >0){
            for(int k=0;k<tlist.getLength() k++){
              if(NodeOld.equals(tlist.item(k).getNodeName())){
               list.item(Index).replaceChild(tlist.item(k),
	       NodeNew);
               break;
              }
            }
           }

            }else{


              NodeList tlist=list.item(DefaultBegin).
	      getChildNodes() 
          if(tlist.getLength() >0){
           for(int k=0;k<tlist.getLength() k++){
             if(NodeOld.equals(tlist.item(k).getNodeName())){
              list.item(DefaultBegin).replaceChild
	      (tlist.item(k),NodeNew);
              break;
             }
           }
           }


            }
         }
      }
     }catch(Exception e){
       System.out.println("替换节点出错");
     }
   }


   public boolean setMark(int index)
   {
    NodeList list=doc.getElementsByTagName(markName);
   if(list.getLength() >0&&index<=list.getLength()-
    1&&index>=0 ) {
     Index=index;
     return true;
   }
    return false;
   }


   public boolean setMark(String name,String value)
   {
     if(value!=null&&value.length() >0){
     try{
     int i=0;
     NodeList list=doc.getElementsByTagName(markName);
     boolean attrs=false;
     boolean find=false;
     if(name!=null&&name.length() >0) attrs=true;
     if(list.getLength() >0){
       for(i=0;i<list.getLength() i++){
         if(attrs){
          if(value.equals(((Element)list.item(i)).
	  getAttribute(name))){
            find=true;
            break;
          }
         }
         else{
           if(value.equals(list.item(i).getNodevalue())){
             find=true;
             break;
           }
         }
       }
       if(find){
         Index=i;
         return true;
        }else{
          return false;
        }
     }
     }catch(Exception e){
       System.out.println("setMark(String name,
        String value)无效");
       return false;
     }
     }
     return false;
   }
   public boolean setMarkAdv(String[] name,String[] value,
    String operation){
    int tempindex=Index;
    try{
     if(name!=null&&name.length >0&&value!=null&&value.
     length >0&&name.length ==value.length){
       if(operation==null||operation.length() ==0) 
       operation ="and";
       if(!operation.equals("and")&&!operation.equals("or")) 
       operation="and";
       if(operation.equals("and")){
         boolean find=true;
         int[] results=new int[name.length];
         for(int i=0;i<name.length i++){
           if(setMark(name[i],value[i])){
             results[i]=Index 
             if(i>0){
               if(results[i]!=results[i-1]){
                 find=false;
                 break;
                 }
             }
           }else{
             find=false;
             break;
           }
         }
         if(find){
           return true;
         }else{
           Index=tempindex;
           return false;
         }
       }else{
         boolean thefind=false;
         for(int j=0;j<name.length j++){
            if(setMark(name[j],value[j])){
              thefind=true;
              break;
            }
         }
         if(thefind){
           return true;
         }else{
           return false;
         }
       }
     }

     return false;
    }catch(Exception ex){
      System.out.println("setMarkAdv(String[] name,
      String[] value,String operation)出错:"+ex.getMessage());
      Index=tempindex;
      return false;
    }
   }

   public void setMarkSign(String NodeName)
   {
     markName=NodeName;
   }
   public document.nbspCreatedocument.){
     try{
     document.nbspnode=((document.Class.forName
     ("com.ibm.xml.dom.document.mpl").newInstance()) 
     return node;

     }catch(Exception ex){
       System.out.print("找不到com.ibm.xml.dom.document.mpl");
       return null;
     }
   }
   public Element CreateElement(String name){
     return doc.createElement(name);
   }
   public Comment CreateComment(String name){
     return doc.createComment(name);
   }
   public Text CreateText(String name){
     return doc.createTextNode(name);
   }
   public Attr CreateAttr(String name){
     return doc.createAttribute(name) 
   }
   public void Output(String path){
     Output(path,encoding,doc,false);
   }
   public void Output(){
     Output(filepath,encoding,doc,false);
   }
   public void setEncoding(String encod){
     encoding=encod;
   }
   public void isEnableMakeUp(){
     EnableMakeUp=true;
   }
   public void isNotEnableMakeUp(){
     EnableMakeUp=false;
   }
   public void Output(String path,Node docu){
     Output(path,encoding,docu,false);
   }
   public void Output(String path,Node docu,boolean noTop){
     Output(path,encoding,docu,noTop);
   }
   public void Output(String path,String NodeName,
   boolean noTop){
     NodeList list=doc.getElementsByTagName(NodeName);
     Node tempnode;
     if(list.getLength() >0){
     if(NodeName.equals(markName)){
       tempnode=list.item(getIndex());
     }else{
       tempnode=list.item(DefaultBegin);
     }
     Output(path,encoding,tempnode,noTop);
     }
   }
   public void Output(String path,String NodeName,
   int indexs,boolean noTop){
     NodeList list=doc.getElementsByTagName(NodeName);
     Node tempnode;
     if(list.getLength() >0){
       if(indexs<=list.getLength() -1){
         tempnode=list.item(indexs);
       }
       else{
         if(NodeName.equals(markName)){
           tempnode=list.item(getIndex());
         }else{
           tempnode=list.item(DefaultBegin);
         }
       }
     Output(path,encoding,tempnode,noTop);
     }
   }



   private void Output(String path,String encod,
   Node docu,boolean noTop){
     try{
     if(path!=null&&path.length()>0){
       filepath=path;
     }
     if(encod!=null&&encod.length() >0){
       encoding =encod;
     }
     XmlBuilder builder=new XmlBuilder();
     if(!EnableMakeUp){
       builder.setIndent("");
       builder.setlineSeparator("");
     }
     builder.setXmlHeader(header);
     builder.printDOMTree(docu,noTop);

     String result=builder.getXmlResult() 



     XmlOutput out=new XmlOutput(filepath);
     out.setEncoding(encoding);
     out.Output(result);
     }catch(Exception ee){
       System.out.println(ee.getMessage());
       System.out.println("写入Xml文件:"+filepath+" 出错");
     }
   }
   public int getIndex(){
     return Index;
   }
   public String getCurrentNodeName(){
     return markName 
   }
   public document.nbspgetdocument.ource(){
     return doc 
   }
   public void setHeader(String Header){
     if(Header!=null&&Header.length() >0){
       header=Header;
     }
   }
}
XMLToolFactory.class 代码如下:
package com.ceic.workflow.xml;

import com.ceic.workflow.xml.Tool.XMLToolTest;
import java.util.*;
/**
 * XMLTool的工厂类。为其它类提供XML处理工具的 运算和实现部分的类。
 */
public class XMLToolFactory
{
   private static Hashtable table;
   private static String defaultType;
   private static String ower;
   /**
    * @roseuid 3ECC2FC101BF
    */
   private  XMLToolFactory()
   {

   }
   /**
    * 获得一个常用XMLTool.
    * @return com.ceic.workflow.xml.XMLTool
    * @roseuid 3ECC2243019B
    */
   public static XMLTool getXMLTool()
   {
     try{
      return ((XMLTool)Class.forName(table.get(ower).
      toString()).newInstance());
     }catch(Exception ee){
       System.out.println("获得常用XMLTool出错");
       return null;
     }
   }
   /**
    * 获得一个XMLTool.通过参数获得XMLTool的一个实现子类.
    * @param type - XMLTool已实现子类在XMLToolFactory中的type名
    * @param classname -
    * XMLTool实现子类的class名(包含package名),
    * 如com.ceic.workflow.xml.tool.XMLToolTest
    * .默认为null或空字符串。
    * @return com.ceic.workflow.xml.XMLTool
    * @roseuid 3ECC2243019B
    */
   public static XMLTool getXMLTool(String type, 
    String classname)
   {
     try{
      if(type==null||type.length() <=0){
        type=defaultType;
      }
      if(table.containsKey(type)){
        return ((XMLTool)Class.forName(table.get(type).
	toString()).newInstance());
      }
      if(classname!=null&&classname.length() >0){
        try{
        XMLTool temp=((XMLTool)Class.forName(classname).
	 newInstance());
        if(type!=null&&type.length() >0){
          table.put(type,classname);
        }
        return temp;
        }catch(Exception ee){
          System.out.println(ee.getMessage() );
          System.out.println("指定的XMLTool不存在");
          return null;
        }
      }
      return null;
      }catch(Exception e){
         System.out.println(e.getMessage() );
        System.out.println("指定的XMLTool不存在");
        return null;
     }
   }
   public static String getDefaultType(){
     return defaultType;
   }

   static
   {
     table=new Hashtable();
     table.put("test","com.ceic.workflow.xml.Tool.
     XMLToolTest");
     table.put("show","com.ceic.workflow.xml.Tool.
     XMLToolShow");
     defaultType="test";
     ower="show";
   }
}
       
       


  到现在为止,xmlparser和xmltool介绍完了。下一次介绍一下xmlbuilder.class,xmloutput.class和针对它们做的一些应用。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值