Java 對xml文件的讀寫操做

/**
 * 描述:數據庫初始化基本類
 * 
 * @做者 王羣
 * @建立日期 2010-04-08
 * @修改人 xxx
 * @修改日期 xxx
 * @檢查人 xxx
 * @檢查日期 xxx
 */
import java.sql.SQLException;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.oumasoft.bstmanage.ibatis.SqlMapConfig;
import com.oumasoft.bstmanage.ibatis.data.JsgnPo;
import com.oumasoft.bstmanage.ibatis.data.Test;

import java.util.*;
import org.w3c.dom.*;
import java.io.*;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.parsers.*;
import javax.xml.transform.dom.*;
import org.apache.log4j.Logger;
import com.oumasoft.bstmanage.ibatis.dao.ClientDao;

public class InitDBDao{
 static Logger logger = Logger.getLogger(ClientDao.class.getName());
 static SqlMapClient sqlMap = null;
 private static File file = null;//讀寫文件
 private static DocumentBuilderFactory factory = null;
 private static DocumentBuilder builder = null;
 
 /**
  * 將修改的內容添加到xml文件中
  * @param document xml節點
  * @param filename 文件路徑
  * @return 是否寫入成功
  */
 public static boolean doc2XmlFile(Document document, String filename) {
  boolean flag = true;
  try {
   /** 將document中的內容寫入文件中 */
   TransformerFactory tFactory = TransformerFactory.newInstance();
   Transformer transformer = tFactory.newTransformer();
   /** 編碼 */
   //transformer.setOutputProperty(OutputKeys.ENCODING, "GBK");
   DOMSource source = new DOMSource(document);
   //判斷路徑開頭有沒有「/」若是有則去掉
   filename = "C".equals(filename.charAt(0)) ? filename : filename.substring(1);   
   StreamResult result = new StreamResult(new FileOutputStream(filename));
   transformer.transform(source, result);   
  } catch (Exception ex) {
   flag = false;
   ex.printStackTrace();
  }
  return flag;
 }

 /**
  * 讀取xml文件
  * @param filename 文件路徑
  * @return 文件節點
  */
 public static Document load(String filename) {  
  Document document = null;
  try {
   factory = DocumentBuilderFactory.newInstance();
   builder = factory.newDocumentBuilder();
   //判斷路徑開頭有沒有「/」若是有則去掉
   filename = "C".equals(filename.charAt(0)) ? filename : filename.substring(1);
   document = builder.parse(new FileInputStream(filename)); 
   document.normalize();
  } catch (Exception ex) {
   ex.printStackTrace();
   logger.error("找不到文件!");
  }
  return document;
 }
 
 /**
  * 添加新的節點
  * 根節點下沒有節點的話直接添加
  * 根節點下沒有重名的直接添加
  * 有重名的節點則更新節點屬性
  * @param filePath 文件路徑
  * @param nodeName 添加、更新的節點名
  * @param attr 屬性集合
  * @return 是否成功
  */
 public static boolean xmlAddDemoAttri(String filePath,String nodeName,Map<String, String> attr) {
  Document document = load(filePath);
  Node root = document.getDocumentElement();
  //建立節點元素,並命名
  Element element =document.createElement(nodeName);
  //向節點中添加屬性
  for (Object key : attr.keySet().toArray()) {
   element.setAttribute(key.toString(), attr.get(key));
  }
  //找到根節點
  NodeList nodeList = document.getElementsByTagName("Context");
  //先判斷根節點下有沒有子節點,沒有的話直接添加
  Node rootNode = nodeList.item(0);
  if(!root.hasChildNodes()){
   nodeList.item(0).appendChild(element);
  }else{
   //若是有重複的節點,flag=true;
   boolean flag = false;
   NodeList rootChs = rootNode.getChildNodes(); 
   //循環根節點下的全部子節點 
   for (int i = 0; i < rootChs.getLength(); i++) {
    Node node = rootChs.item(i);
    //若是沒有重名,而且是最後一個節點的就添加
    if(!nodeName.equals(node.getNodeName()) && !flag && (i+1) == rootChs.getLength()){
     nodeList.item(0).appendChild(element);
    }else if(nodeName.equals(node.getNodeName())){ 
      
     //有重名的就看name屬性,name同樣就修改屬性
     if(node.hasAttributes()){
      //若是有屬性項,判斷name屬性值,若是name的值相同,則修改其餘屬性
      if(null != node.getAttributes().getNamedItem("name") && attr.get("name").equals(node.getAttributes().getNamedItem("name").getNodeValue())){
       // 生成一個屬性對象
       Attr chAttr = null;
       //向節點中添加屬性
       for (Object key : attr.keySet().toArray()) {
        //不更新name屬性
        if(!"name".equals(key.toString())){
         chAttr = document.createAttribute(key.toString());
         chAttr.setValue(attr.get(key));
        }
       }
       node.getAttributes().setNamedItem(chAttr);
      }else if(null != node.getAttributes().getNamedItem("name") && !attr.get("name").equals(node.getAttributes().getNamedItem("name").getNodeValue()) && !flag && (i+1) == rootChs.getLength()){
      //若是name的值不相同,且都沒有相同的節點,添加新的節點
       nodeList.item(0).appendChild(element);
      }
     }
    }
   }
  }
  // 將修改的內容添加到xml文件中
  return doc2XmlFile(document, filePath);
 }
 
 /**
  * 查詢xml文件中指定節點的制定屬性值,對於重名的節點能夠經過conditions屬性進行篩選
  * @param filePath xml文件路徑
  * @param nodeName 節點名
  * @param conditions 條件屬性,只有所有符合纔會返回attr指定的屬性的值
  * @param attr 要查詢的屬性
  * @return 查詢的屬性的值
  */
 public static String xmlReadDemoAttri(String filePath,String nodeName,Map<String, String> conditions,String attr) {
  String returnStr = null;
  Document document = load(filePath);
  Node root = document.getDocumentElement();
  //找到根節點
  NodeList nodeList = document.getElementsByTagName("Context");
  //先找到context根節點
  Node rootNode = nodeList.item(0);
  if(!root.hasChildNodes()){
   //沒有子節點
  }else{
   NodeList rootChs = rootNode.getChildNodes(); 
   //循環根節點下的全部子節點 
   for (int i = 0; i < rootChs.getLength(); i++) {
    Node node = rootChs.item(i);
    //查找Resource鏈接節點 
    if(nodeName.equals(node.getNodeName())){
     boolean isOk = false;
     //對於有重名的節點,將節點的屬性與條件比較
     for (Object key : conditions.keySet().toArray()) {
      String value = conditions.get(key);
      String nodeValue = node.getAttributes().getNamedItem(key.toString()).getNodeValue();
      
      //若是相同的屬性,可是值不同則退出循環
      if(!value.equals(nodeValue)){
       isOk = true;
       break;
      }
     }
     //節點中屬性與條件屬性一旦出現不同這中斷本次循環
     if(isOk){
      continue;
     }else{
      if(null != node.getAttributes() && null != node.getAttributes().getNamedItem(attr)){
       returnStr = node.getAttributes().getNamedItem(attr).getNodeValue();
      }
     }
    }    
   }
  }
  return returnStr;
 }

 
 /**
  * 對比xml文件中指定節點name屬性值與指定值是否相等
  * @param filePath xml文件路徑
  * @param nodeName 節點名
  * @param nameValue 制定的name值
  * @return boolean值,相同返回True
  */
 public static boolean xmlReadDemoEqualsByName(String filePath,String nodeName,String nameValue) {
  boolean returnStr = false;
  Document document = load(filePath);
  Node root = document.getDocumentElement();
  //找到根節點
  NodeList nodeList = document.getElementsByTagName("Context");
  //先找到context根節點
  Node rootNode = nodeList.item(0);
  if(!root.hasChildNodes()){
   //沒有子節點
   return false;
  }else{
   NodeList rootChs = rootNode.getChildNodes(); 
   //循環根節點下的全部子節點 
   for (int i = 0; i < rootChs.getLength(); i++) {
    Node node = rootChs.item(i);
    //查找Resource鏈接節點 
    if((nodeName.toLowerCase()).equals(node.getNodeName().toLowerCase())){
     if(node.hasAttributes() && null != node.getAttributes().getNamedItem("name")){
      String attrValue = node.getAttributes().getNamedItem("name").getNodeValue();      
      //若是name屬性值相同,將標誌設置爲true
      if(nameValue.equals(attrValue)){
       returnStr = true;
      }
     }
    }    
   }
  }
  return returnStr;
 }
}
相關文章
相關標籤/搜索