xmlstream.java

来自「java开发的办公系统 1.系统管理 (地区管理,部门管理,菜单管理,用户管理」· Java 代码 · 共 258 行

JAVA
258
字号
package com.vere.util;
import java.io.*;
import java.util.*;
import java.util.logging.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;

/**
 * 负责对XML文件的操作
 */
public class XMLStream {
  /**
   * The Logger instance. All log messages from this class are routed through
   * this member. The Logger namespace is com.vere.util
   */
  private Logger log = Logger.getLogger("com.vere.util");

  private Document doc;
  private InputStream inputstream;
  /**
   * 构造函数
   * @param is  输入流 java.io.Inputstream
   * @throws Exception
   */
  public XMLStream (InputStream is)throws Exception{
    if (is == null)
        throw new Exception("XMLStream类的构建参数为null。");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        doc = db.parse(is);
    }catch(ParserConfigurationException e){
        log.log(Level.SEVERE,"XMLStream类的构建方法出错:"+e.toString());
        throw new Exception("XMLStream类的构建方法出错:"+e.toString());
    }catch(Exception e){
        log.log(Level.SEVERE,"XMLStream类的构建方法出错:"+e.toString());
        throw new Exception("XMLStream类的构建方法出错:"+e.toString());
    }
    inputstream = is;
  }
  /**
   * 获得一个Field的数值
   * @param path  路径
   * @param name  名称
   * @return {name,value,type}
   * @throws Exception
   */
  public String[] getField(String path,String name) throws Exception{
    Node fieldNode = findNode((Node)doc.getDocumentElement(),parsePath(path),0,name);
    if(fieldNode == null)return null;
    return getFieldContent(fieldNode);
  }
   /**
    * 有path的前提条件下,增加一个field
    * @param path
    * @param name
    * @param value
    * @param type
    * @throws Exception
    */
  public void addField(String path,String name,String value,String type) throws Exception{
    String pathArr[]= parsePath(path);
    //path2为父接点的路径
    String[] path2 = new String[pathArr.length-1];
    for(int i=0;i<path2.length;i++){
      path2[i]=pathArr[i];
    }
    Node superNode = findNode((Node)doc.getDocumentElement(),path2,0);
    if(superNode !=null)
      insertField(superNode,pathArr[pathArr.length-1],name,value,type);
  }
  /**
   * 解析path
   * @param path path是以“.”分隔的字符串
   * @return 路径的结果数组
   * @throws Exception
   */
  private String[] parsePath(String path){
    StringTokenizer st = new StringTokenizer(path,".");
    int i = 0;
    String[] pathArr = new String[st.countTokens()];
    while (st.hasMoreTokens()) {
      pathArr[i++] = st.nextToken();
    }
    return pathArr;
  }
  /**
   * 根据path和name找到doc中的那个node
   * @param node 当前搜索的结点
   * @param path 字符串数组,表示路径
   * @param index 是路径数组的指针,表示当前搜索到数组中的哪一项
   * @param name 名称
   * @return node 节点
   */
  private Node findNode(Node node,String[] path,int index,String name){
    Node resultNode = null;
    if(node.getNodeName().equalsIgnoreCase(path[index])){
      if (index + 1 == path.length) {
        //如果和路径匹配,而且已经到了数组的最后一个,说明已经找到
        if(((Element)node).getAttribute("name").equalsIgnoreCase(name))
          resultNode = node;
      }
      else {
        //如果和路径匹配,但是还是没有到数组的最后一个,继续查找子接点
        NodeList childNodeList = node.getChildNodes();
        for (int i = 0; i < childNodeList.getLength(); i++){
          Node childNode = childNodeList.item(i);
          if (childNode instanceof Element){
            resultNode = findNode(childNode,path,index+1,name);
            if(resultNode!=null)
              break;
          }
        }
      }
    }
    return resultNode;
  }
  /**
   * 获取node中的field的信息
   * @param node 当前搜索的结点
   * @return content
   */
  private String[] getFieldContent(Node node){
    String[] content = new String[3];
    content[0] = ((Element)node).getAttribute("name");
    content[1] = ((Element)node).getAttribute("value");
    content[2] = ((Element)node).getAttribute("type");
    return content;
  }
  /**
   * 根据path找到node
   * @param node 当前搜索的结点
   * @param path 字符串数组,表示路径
   * @param index 是路径数组的指针,表示当前搜索到数组中的哪一项
   * @return node
   */
  private Node findNode(Node node,String[] path,int index){
    Node resultNode = null;
    if(node.getNodeName().equalsIgnoreCase(path[index])){
      if (index + 1 == path.length) {
        //如果和路径匹配,而且已经到了数组的最后一个,说明已经找到
        resultNode = node;
      }
      else {
        //如果和路径匹配,但是还是没有到数组的最后一个,继续查找子接点
        NodeList childNodeList = node.getChildNodes();
        for (int i = 0; i < childNodeList.getLength(); i++){
          Node childNode = childNodeList.item(i);
          if (childNode instanceof Element){
            resultNode = findNode(childNode,path,index+1);
            if(resultNode!=null)
              break;
          }
        }
      }
    }
    return resultNode;
  }
  /**
   * 插入一个field
   * @param superNode 要插入的父结点
   * @param nodeName
   * @param name
   * @param value
   * @param type
   */
  private void insertField(Node superNode,String nodeName ,String name,String value,String type){
    Element element = doc.createElement(nodeName);
    element.setAttribute("name",name);
    element.setAttribute("value",value);
    element.setAttribute("type",type);
    ((Element)(superNode)).appendChild(element);
  }
  /**
   * 将document中的数据写入到outputstream中去
   * @param os 输出流(OutputStream)
   * @throws Exception
   */
  public void store(OutputStream os)throws Exception{
    String content = "<?xml version=\"1.0\" encoding=\"GB2312\"?>"+doc.getDocumentElement().toString();
    byte[] bytes = content.getBytes();
    os.write(bytes);
    os.flush();
  }
  /**
   * 增加一个path,其中path的上一级path必须存在
   * @param path
   * @throws Exception
   */
  public void  addPath(String  path) throws Exception{
    String superPath = path.substring(0,path.lastIndexOf("."));
    String[] superpathArr= parsePath(superPath);
    Node superNode = findNode((Node)doc.getDocumentElement(),superpathArr,0);
    if(superNode == null){
      //找不到父path
      log.log(Level.SEVERE,"父目录不存在无法插入当前目录 "+path);
      throw new Exception("父目录不存在无法插入当前目录 ");
    }
    if(findNode(doc.getDocumentElement(),parsePath(path),0)!=null){
      //已经有此path节点
      log.log(Level.SEVERE,"此目录已经存在 "+path);
      return ;
      //throw new Exception("此目录已经存在");
    }
    Element pathElement = doc.createElement(path.substring(path.lastIndexOf(".")+1,path.length()));
    ((Element)superNode).appendChild(pathElement);
  }
  /**
   * 删除一个Field
   * @param path
   * @param name
   * @throws Exception
   */
  public void  deleteField(String path,String name) throws Exception{
    String superPath = path.substring(0,path.lastIndexOf("."));
    String[] superpathArr= parsePath(superPath);
    Node superNode = findNode((Node)doc.getDocumentElement(),superpathArr,0);
    if(superNode == null){
      //找不到父field
      log.log(Level.SEVERE,"删除field出错,父目录不存在无法删除当前节点 "+path+":"+name);
      throw new Exception("父目录不存在无法当前节点");
    }
    Node thisNode = findNode((Node)doc.getDocumentElement(),parsePath(path),0,name);
    if(thisNode == null){
      log.log(Level.SEVERE,"删除field出错,不存在当前节点:"+path+":"+name);
      throw new Exception("不存当前节点");
    }
    superNode.removeChild(thisNode);
  }
  /**
   * 删除一个Path,其父节点必须存在,否则抛出异常
   * @param path
   * @throws Exception
   */
  public void  deletePath(String path) throws Exception{
    String superPath = path.substring(0,path.lastIndexOf("."));
    String[] superpathArr= parsePath(superPath);
    Node superNode = findNode((Node)doc.getDocumentElement(),superpathArr,0);
    if(superNode == null){
      //找不到父field
      log.log(Level.SEVERE,"删除Path出错,父目录不存在"+path);
      throw new Exception("父目录不存在无法当前节点");
    }
    Node thisNode = findNode((Node)doc.getDocumentElement(),parsePath(path),0);
    if(thisNode == null){
      log.log(Level.SEVERE,"删除Path出错,不存在当前节点:"+path);
      return ;
    }
    superNode.removeChild(thisNode);
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?