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;
 }
}
相关文章
相关标签/搜索