Java 对xml文件的读写操作

  1. /** 
  2.  * 描述:数据库初始化基本类 
  3.  *  
  4.  * @作者 王群 
  5.  * @创建日期 2010-04-08 
  6.  * @修改人 xxx 
  7.  * @修改日期 xxx 
  8.  * @检查人 xxx 
  9.  * @检查日期 xxx 
  10.  */  
  11. import java.sql.SQLException;  
  12.   
  13. import com.ibatis.sqlmap.client.SqlMapClient;  
  14. import com.oumasoft.bstmanage.ibatis.SqlMapConfig;  
  15. import com.oumasoft.bstmanage.ibatis.data.JsgnPo;  
  16. import com.oumasoft.bstmanage.ibatis.data.Test;  
  17.   
  18. import java.util.*;  
  19. import org.w3c.dom.*;  
  20. import java.io.*;  
  21. import javax.servlet.http.HttpServletRequest;  
  22. import javax.xml.transform.stream.*;  
  23. import org.w3c.dom.*;  
  24. import javax.xml.transform.*;  
  25. import javax.xml.parsers.*;  
  26. import javax.xml.transform.dom.*;  
  27. import org.apache.log4j.Logger;  
  28. import com.oumasoft.bstmanage.ibatis.dao.ClientDao;  
  29.   
  30. public class InitDBDao{  
  31.  static Logger logger = Logger.getLogger(ClientDao.class.getName());  
  32.  static SqlMapClient sqlMap = null;  
  33.  private static File file = null;//读写文件  
  34.  private static DocumentBuilderFactory factory = null;  
  35.  private static DocumentBuilder builder = null;  
  36.    
  37.  /** 
  38.   * 将修改的内容添加到xml文件中 
  39.   * @param document xml节点 
  40.   * @param filename 文件路径 
  41.   * @return 是否写入成功 
  42.   */  
  43.  public static boolean doc2XmlFile(Document document, String filename) {  
  44.   boolean flag = true;  
  45.   try {  
  46.    /** 将document中的内容写入文件中 */  
  47.    TransformerFactory tFactory = TransformerFactory.newInstance();  
  48.    Transformer transformer = tFactory.newTransformer();  
  49.    /** 编码 */  
  50.    //transformer.setOutputProperty(OutputKeys.ENCODING, "GBK");  
  51.    DOMSource source = new DOMSource(document);  
  52.    //判断路径开头有没有“/”如果有则去掉  
  53.    filename = "C".equals(filename.charAt(0)) ? filename : filename.substring(1);     
  54.    StreamResult result = new StreamResult(new FileOutputStream(filename));  
  55.    transformer.transform(source, result);     
  56.   } catch (Exception ex) {  
  57.    flag = false;  
  58.    ex.printStackTrace();  
  59.   }  
  60.   return flag;  
  61.  }  
  62.   
  63.  /** 
  64.   * 读取xml文件 
  65.   * @param filename 文件路径 
  66.   * @return 文件节点 
  67.   */  
  68.  public static Document load(String filename) {    
  69.   Document document = null;  
  70.   try {  
  71.    factory = DocumentBuilderFactory.newInstance();  
  72.    builder = factory.newDocumentBuilder();  
  73.    //判断路径开头有没有“/”如果有则去掉  
  74.    filename = "C".equals(filename.charAt(0)) ? filename : filename.substring(1);  
  75.    document = builder.parse(new FileInputStream(filename));   
  76.    document.normalize();  
  77.   } catch (Exception ex) {  
  78.    ex.printStackTrace();  
  79.    logger.error("找不到文件!");  
  80.   }  
  81.   return document;  
  82.  }  
  83.    
  84.  /** 
  85.   * 添加新的节点 
  86.   * 根节点下没有节点的话直接添加 
  87.   * 根节点下没有重名的直接添加 
  88.   * 有重名的节点则更新节点属性 
  89.   * @param filePath 文件路径 
  90.   * @param nodeName 添加、更新的节点名 
  91.   * @param attr 属性集合 
  92.   * @return 是否成功 
  93.   */  
  94.  public static boolean xmlAddDemoAttri(String filePath,String nodeName,Map<String, String> attr) {  
  95.   Document document = load(filePath);  
  96.   Node root = document.getDocumentElement();  
  97.   //创建节点元素,并命名  
  98.   Element element =document.createElement(nodeName);  
  99.   //向节点中添加属性  
  100.   for (Object key : attr.keySet().toArray()) {  
  101.    element.setAttribute(key.toString(), attr.get(key));  
  102.   }  
  103.   //找到根节点  
  104.   NodeList nodeList = document.getElementsByTagName("Context");  
  105.   //先判断根节点下有没有子节点,没有的话直接添加  
  106.   Node rootNode = nodeList.item(0);  
  107.   if(!root.hasChildNodes()){  
  108.    nodeList.item(0).appendChild(element);  
  109.   }else{  
  110.    //如果有重复的节点,flag=true;  
  111.    boolean flag = false;  
  112.    NodeList rootChs = rootNode.getChildNodes();   
  113.    //循环根节点下的所有子节点   
  114.    for (int i = 0; i < rootChs.getLength(); i++) {  
  115.     Node node = rootChs.item(i);  
  116.     //如果没有重名,并且是最后一个节点的就添加  
  117.     if(!nodeName.equals(node.getNodeName()) && !flag && (i+1) == rootChs.getLength()){  
  118.      nodeList.item(0).appendChild(element);  
  119.     }else if(nodeName.equals(node.getNodeName())){   
  120.         
  121.      //有重名的就看name属性,name一样就修改属性  
  122.      if(node.hasAttributes()){  
  123.       //如果有属性项,判断name属性值,如果name的值相同,则修改其他属性  
  124.       if(null != node.getAttributes().getNamedItem("name") && attr.get("name").equals(node.getAttributes().getNamedItem("name").getNodeValue())){  
  125.        // 生成一个属性对象  
  126.        Attr chAttr = null;  
  127.        //向节点中添加属性  
  128.        for (Object key : attr.keySet().toArray()) {  
  129.         //不更新name属性  
  130.         if(!"name".equals(key.toString())){  
  131.          chAttr = document.createAttribute(key.toString());  
  132.          chAttr.setValue(attr.get(key));  
  133.         }  
  134.        }  
  135.        node.getAttributes().setNamedItem(chAttr);  
  136.       }else if(null != node.getAttributes().getNamedItem("name") && !attr.get("name").equals(node.getAttributes().getNamedItem("name").getNodeValue()) && !flag && (i+1) == rootChs.getLength()){  
  137.       //如果name的值不相同,且都没有相同的节点,添加新的节点  
  138.        nodeList.item(0).appendChild(element);  
  139.       }  
  140.      }  
  141.     }  
  142.    }  
  143.   }  
  144.   // 将修改的内容添加到xml文件中  
  145.   return doc2XmlFile(document, filePath);  
  146.  }  
  147.    
  148.  /** 
  149.   * 查询xml文件中指定节点的制定属性值,对于重名的节点可以通过conditions属性进行筛选 
  150.   * @param filePath xml文件路径 
  151.   * @param nodeName 节点名 
  152.   * @param conditions 条件属性,只有全部符合才会返回attr指定的属性的值 
  153.   * @param attr 要查询的属性 
  154.   * @return 查询的属性的值 
  155.   */  
  156.  public static String xmlReadDemoAttri(String filePath,String nodeName,Map<String, String> conditions,String attr) {  
  157.   String returnStr = null;  
  158.   Document document = load(filePath);  
  159.   Node root = document.getDocumentElement();  
  160.   //找到根节点  
  161.   NodeList nodeList = document.getElementsByTagName("Context");  
  162.   //先找到context根节点  
  163.   Node rootNode = nodeList.item(0);  
  164.   if(!root.hasChildNodes()){  
  165.    //没有子节点  
  166.   }else{  
  167.    NodeList rootChs = rootNode.getChildNodes();   
  168.    //循环根节点下的所有子节点   
  169.    for (int i = 0; i < rootChs.getLength(); i++) {  
  170.     Node node = rootChs.item(i);  
  171.     //查找Resource连接节点   
  172.     if(nodeName.equals(node.getNodeName())){  
  173.      boolean isOk = false;  
  174.      //对于有重名的节点,将节点的属性与条件比较  
  175.      for (Object key : conditions.keySet().toArray()) {  
  176.       String value = conditions.get(key);  
  177.       String nodeValue = node.getAttributes().getNamedItem(key.toString()).getNodeValue();  
  178.         
  179.       //如果相同的属性,但是值不一样则退出循环  
  180.       if(!value.equals(nodeValue)){  
  181.        isOk = true;  
  182.        break;  
  183.       }  
  184.      }  
  185.      //节点中属性与条件属性一旦出现不一样这中断本次循环  
  186.      if(isOk){  
  187.       continue;  
  188.      }else{  
  189.       if(null != node.getAttributes() && null != node.getAttributes().getNamedItem(attr)){  
  190.        returnStr = node.getAttributes().getNamedItem(attr).getNodeValue();  
  191.       }  
  192.      }  
  193.     }      
  194.    }  
  195.   }  
  196.   return returnStr;  
  197.  }  
  198.   
  199.    
  200.  /** 
  201.   * 对比xml文件中指定节点name属性值与指定值是否相等 
  202.   * @param filePath xml文件路径 
  203.   * @param nodeName 节点名 
  204.   * @param nameValue 制定的name值 
  205.   * @return boolean值,相同返回True 
  206.   */  
  207.  public static boolean xmlReadDemoEqualsByName(String filePath,String nodeName,String nameValue) {  
  208.   boolean returnStr = false;  
  209.   Document document = load(filePath);  
  210.   Node root = document.getDocumentElement();  
  211.   //找到根节点  
  212.   NodeList nodeList = document.getElementsByTagName("Context");  
  213.   //先找到context根节点  
  214.   Node rootNode = nodeList.item(0);  
  215.   if(!root.hasChildNodes()){  
  216.    //没有子节点  
  217.    return false;  
  218.   }else{  
  219.    NodeList rootChs = rootNode.getChildNodes();   
  220.    //循环根节点下的所有子节点   
  221.    for (int i = 0; i < rootChs.getLength(); i++) {  
  222.     Node node = rootChs.item(i);  
  223.     //查找Resource连接节点   
  224.     if((nodeName.toLowerCase()).equals(node.getNodeName().toLowerCase())){  
  225.      if(node.hasAttributes() && null != node.getAttributes().getNamedItem("name")){  
  226.       String attrValue = node.getAttributes().getNamedItem("name").getNodeValue();        
  227.       //如果name属性值相同,将标志设置为true  
  228.       if(nameValue.equals(attrValue)){  
  229.        returnStr = true;  
  230.       }  
  231.      }  
  232.     }      
  233.    }  
  234.   }  
  235.   return returnStr;  
  236.  }  
  237. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值