欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java操作XML實(shí)例代碼

 更新時(shí)間:2014年01月26日 15:19:26   作者:  
這篇文章主要介紹了java操作XML實(shí)例代碼,有需要的朋友可以參考一下

最近一直在做高效平臺(tái)的框架,其實(shí)意識(shí)到我要做一個(gè)簡(jiǎn)單的框架的時(shí)候是在我已經(jīng)做完我認(rèn)為的一版界面之后,開(kāi)始以為我要做的是一個(gè)可配置的首頁(yè)展示,但是吭哧吭哧做了兩個(gè)星期,大概功能實(shí)現(xiàn)了之后,才發(fā)現(xiàn)要做的不是這個(gè),哎,需求不清楚害死人啊,但是這兩個(gè)星期并沒(méi)有白白浪費(fèi),也從中學(xué)到了很多東西,下面主要介紹讀取XML。
在做系統(tǒng)的時(shí)候,經(jīng)常會(huì)遇到讀取xml的需求,一開(kāi)始是讀取,于是我上網(wǎng)開(kāi)始查詢讀取,接著查詢刪除,接著查詢修改,當(dāng)把這些代碼查的差不多的時(shí)候,我發(fā)現(xiàn),我為什么不把這些的操作都封裝到一個(gè)類里,使用的時(shí)候直接調(diào)用,豈不是更好,感覺(jué)之前腦袋都秀逗了,分別查了那么多,還一個(gè)個(gè)的調(diào)試,抱著這個(gè)心態(tài)繼續(xù)上網(wǎng)查(因?yàn)槲艺嫘母杏X(jué)網(wǎng)上肯定有,如果我自己封裝的話腦袋就真的進(jìn)水了)。
源代碼展示:

復(fù)制代碼 代碼如下:

package com.gxpt.struts2;
import java.io.File;
import java.io.FileWriter;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class testAddDeleteXML {
private Document document;
 private String filePath; //文件所在的實(shí)際物理路徑
 //private WriteLog writelog;
 public static void main(String[] args) throws DocumentException {
  //String filepath = System.getProperty("user.dir")+"/XmlFiles/LocalServicesConfig.xml";
  String filepath ="F:\\JAVA項(xiàng)目\\高校平臺(tái)\\demo\\gxpt\\WebContent\\limits\\manager.txt";
  testAddDeleteXML operator = new testAddDeleteXML(filepath);
  operator.getXmlFile();

  
//  Map map = new HashMap();
//  map.put("id", "m1");
//  map.put("name","module1");
//  map.put("url", "index1.jsp");
//  operator.addChild("div", "div9","module", "",map);
  //operator.updateChild("style", "", "div", "asdfasdf",1);  

  operator.deleteChildOne("style", "","div","div11");
  //operator.deleteChild("div", "div9","module");
  //String str = operator.getChild("div", "div8", "module");
  //System.out.println(str);
  //Element root = document.getRootElement();//獲取根節(jié)點(diǎn)名稱

  
 }

 

 public  testAddDeleteXML(String filepath){
  this.document = null;
  this.filePath = filepath;
  //writelog = new WriteLog();
 }
 /**
 * 創(chuàng)建XML文件
 * @param rootName:根節(jié)點(diǎn)名稱
 */
 public void createXMLFile(String rootName) {
    if(!fileExist()){
     this.document = DocumentHelper.createDocument();
     this.document.addElement(rootName);
     saveXMLFile(this.document);
    }
 }
/**
* 獲取已存在的XML文檔
* @return
*/
 public Document getXmlFile() {
    if (fileExist()) {
     SAXReader reader = new SAXReader();
     try {
      this.document = reader.read(new File(filePath));
     } catch (DocumentException e) {
    //  String loginfo = StackTraceToString.getExceptionTrace(e);
    //  writelog.writeLogToEnd("LocalServerManager", loginfo);
     }finally{
      reader = null;
     }
    } else {
     //寫(xiě)日志
    // String loginfo = "XML file does not exist,read error!";
   //  writelog.writeLogToEnd("LocalServerManager",loginfo);
     System.exit(0);
    }
    return this.document;
 }

 /**
 * 添加元素
 * @param fatherPath:父節(jié)點(diǎn)名稱
 * @param fatherattr:父節(jié)點(diǎn)屬性
 * @param childName:要添加的節(jié)點(diǎn)名稱
 * @param childValue:要添加的節(jié)點(diǎn)值
 */
 public void addChild(String fatherNode, String fatherAttr,String childName, String childValue,Map mapAttr) {
    ChildOperator(fatherNode,fatherAttr,childName,childValue,"add",mapAttr,0);
 }
 /**
 * 修改元素
 * @param fatherPath:父節(jié)點(diǎn)名稱
 * @param fatherattr:父節(jié)點(diǎn)屬性
 * @param childName:要修改的節(jié)點(diǎn)名稱
 * @param childValue:要修改成的節(jié)點(diǎn)值
 */
 public void updateChild(String fatherNode, String fatherAttr,String childName, String childValue,int updatId) {
    ChildOperator(fatherNode,fatherAttr,childName,childValue,"update",null,updatId);
 }
 /**
 * 刪除元素
 * @param fatherPath:父節(jié)點(diǎn)名稱
 * @param fatherattr:父節(jié)點(diǎn)屬性
 * @param childName:要?jiǎng)h除的節(jié)點(diǎn)名稱
 */
 public void deleteChild(String fatherNode, String fatherAttr,String childName) {
    ChildOperator(fatherNode,fatherAttr,childName,"","delete",null,0);
 }
 /**
 * 刪除元素
 * @param fatherPath:父節(jié)點(diǎn)名稱
 * @param fatherattr:父節(jié)點(diǎn)屬性
 * @param childName:要?jiǎng)h除的節(jié)點(diǎn)名稱
 */
 public void deleteChildAll(String fatherNode, String fatherAttr,String childName) {
    ChildOperator(fatherNode,fatherAttr,childName,"","deleteAll",null,0);
 }

 
 /**
 * 刪除某個(gè)元素
 * @param fatherPath:父節(jié)點(diǎn)名稱
 * @param fatherattr:父節(jié)點(diǎn)屬性
 * @param childName:要?jiǎng)h除的節(jié)點(diǎn)名稱
 */
 public void deleteChildOne(String fatherNode, String fatherAttr,String childName,String childValue) {
    ChildOperator(fatherNode,fatherAttr,childName,childValue,"deleteOne",null,0);
 }
 /**
 * 獲取某個(gè)元素?cái)?shù)值
 * @param fatherPath:父節(jié)點(diǎn)名稱
 * @param fatherattr:父節(jié)點(diǎn)屬性
 * @param childName:要?jiǎng)h除的節(jié)點(diǎn)名稱
 */
 public String getChild(String fatherNode, String fatherAttr,String childName) {
    String result = "";
    result = ChildOperator(fatherNode,fatherAttr,childName,"","get",null,0);
    return result;
 }
 /**
 * 子節(jié)點(diǎn)操作
 * @param fatherNode:父節(jié)點(diǎn)名稱
 * @param fatherAttr:父節(jié)點(diǎn)屬性
 * @param childName:要修改的節(jié)點(diǎn)
 * @param childValue:修改后的節(jié)點(diǎn)值
 * @param operator: 要執(zhí)行的操作名稱
 */
 private synchronized String ChildOperator(String fatherNode, String fatherAttr,String childName, String childValue,String operator,Map mapAttr,int updateId) {
    String result="";
    if (this.document == null) {

      return "null";
    }
    Element root = this.document.getRootElement();//獲取根節(jié)點(diǎn)名稱

    if(!root.getName().equals(fatherNode)){ //如果不是在根節(jié)點(diǎn)下添加
     result = XmlElementOperator(root,fatherNode,fatherAttr,childName,childValue,operator,mapAttr);
    }else{
      if(operator.equals("add")){
        Element childelement = root.addElement(childName);//根節(jié)點(diǎn)不存在元素屬性值
        childelement.setAttributeValue("id",childValue);

       
        saveXMLFile(this.document);
      }else if(operator.equals("update")){
        List childelements = root.elements(childName);
       // for(Iterator childs=childelements.iterator();childs.hasNext();){
       //   Element everyone = (Element)childs.next();
        //  everyone.setText(childValue); //修改該元素值
       //   everyone.setAttributeValue("id",childValue);
         Element everyone = (Element)childelements.get(updateId);
         everyone.setAttributeValue("id",childValue);
      //  }
        saveXMLFile(this.document);
      }else if(operator.equals("delete")){
       List childelements = root.elements(childName);//獲取當(dāng)前節(jié)點(diǎn)下的所有子節(jié)點(diǎn),判斷其值,以進(jìn)行修改
       for(Iterator childs=childelements.iterator();childs.hasNext();){
         Element everyone = (Element)childs.next();
         List childelements1 = everyone.elements("module");
         for(Iterator childs1=childelements1.iterator();childs1.hasNext();){
          Element everyone1 = (Element)childs1.next();
          everyone.remove(everyone1);
         }

         
       }

       saveXMLFile(this.document);
      }else if(operator.equals("get")){
       List childelements = root.elements(childName);//獲取當(dāng)前節(jié)點(diǎn)下的所有子節(jié)點(diǎn),判斷其值,以進(jìn)行修改

       for(Iterator childs=childelements.iterator();childs.hasNext();){
        Element everyone = (Element)childs.next();

        result = everyone.getText();
       }
       saveXMLFile(this.document);
      }else if(operator.equals("deleteOne")){

       List childelements = root.elements(childName);//獲取當(dāng)前節(jié)點(diǎn)下的所有子節(jié)點(diǎn),判斷其值,以進(jìn)行修改

       for(Iterator childs=childelements.iterator();childs.hasNext();){
         Element everyone = (Element)childs.next();
         String  divElement = everyone.attributeValue("id");
         if(divElement.equals(childValue)){
          root.remove(everyone);
         }
       }
       saveXMLFile(this.document);
      }else if(operator.equals("deleteAll")){
       List childelements = root.elements();//獲取當(dāng)前節(jié)點(diǎn)下的所有子節(jié)點(diǎn),判斷其值,以進(jìn)行修改

       for(Iterator childs=childelements.iterator();childs.hasNext();){
        Element everyone = (Element)childs.next();
        List childeDiv = everyone.elements();
        for(Iterator childsDiv=childeDiv.iterator();childsDiv.hasNext();){
         Element everyoneDiv = (Element)childsDiv.next();
         everyone.remove(everyoneDiv);
        }
       }
      }
      saveXMLFile(this.document);

    }
    return result;
 } 
 /**
 * 遞歸元素操作
 * @param element:要遞歸的元素
 * @param fatherNode:父節(jié)點(diǎn)名稱
 * @param fatherAttr:父節(jié)點(diǎn)屬性
 * @param childName:要進(jìn)行操作的節(jié)點(diǎn)
 * @param childValue:操作后的節(jié)點(diǎn)值
 * @param operator: 要執(zhí)行的操作名稱
 */
 private synchronized String XmlElementOperator(Element element,String fatherNode,String fatherAttr,String childName,String childValue,String operator,Map mapAttr){
    String result = "";
    List elements = element.elements();
    for(Iterator it=elements.iterator();it.hasNext();){
     Element currentelement = (Element)it.next();
     if(!currentelement.getName().equals(fatherNode)){ //當(dāng)前元素并不是我們要查找的父元素時(shí),繼續(xù)查找
      XmlElementOperator(currentelement,fatherNode,fatherAttr,childName,childValue,operator,mapAttr);//遞歸調(diào)用
     }else{
      if(currentelement.attributeCount()>0){ //當(dāng)前元素存在屬性值時(shí)
       for(Iterator list=currentelement.attributeIterator();list.hasNext();){ //遍歷屬性值
        Attribute attr = (Attribute)list.next(); //獲取屬性值隊(duì)列中的第一個(gè)元素
        if(attr.getValue().equals(fatherAttr)){//根據(jù)屬性值確定惟一的父元素
         if(operator.equals("add")){//添加元素
          Element childelement = currentelement.addElement(childName); //給當(dāng)前元素添加一個(gè)子元素

          childelement.setText(childValue); //設(shè)置子元素的數(shù)值
        Iterator itmapAttr = mapAttr.keySet().iterator();
          while(itmapAttr.hasNext()){
         String key = (String) itmapAttr.next();
         String value = mapAttr.get(key).toString();
          childelement.setAttributeValue(key,value);

        }

//          childelement.setAttributeValue("id", "m1");
//            childelement.setAttributeValue("name", "module1");
//            childelement.setAttributeValue("url", "index1.jsp");
         }else if(operator.equals("update")){//修改某個(gè)元素
          List childelements = currentelement.elements(childName);//獲取當(dāng)前節(jié)點(diǎn)下的所有子節(jié)點(diǎn),判斷其值,以進(jìn)行修改
          for(Iterator childs=childelements.iterator();childs.hasNext();){
           Element everyone = (Element)childs.next();
           everyone.setText(childValue); //修改該元素值
          }
         }else if(operator.equals("delete")){ //刪除某個(gè)指定的元素

          List childelements = currentelement.elements();//獲取當(dāng)前節(jié)點(diǎn)下的所有子節(jié)點(diǎn),判斷其值,以進(jìn)行修改

          for(Iterator childs=childelements.iterator();childs.hasNext();){
           Element everyone = (Element)childs.next();
           currentelement.remove(everyone);
          }
         }else if(operator.equals("get")){
          List childelements = currentelement.elements(childName);//獲取當(dāng)前節(jié)點(diǎn)下的所有子節(jié)點(diǎn),判斷其值,以進(jìn)行修改
          for(Iterator childs=childelements.iterator();childs.hasNext();){
            Element everyone = (Element)childs.next();
           // result = everyone.getText();
            result =everyone.attributeValue("id")+","+result ;
          }
         }
         else{
          //寫(xiě)日志
          //  String loginfo = "XmlFile Operator not exists!";
          //  writelog.writeLogToEnd("LocalServerManager",loginfo);
         }
        }
       }
      }
     }
    }
    saveXMLFile(this.document);
    return result;
 }
 /**
 * 保存XML文件
 * @param document: XML文件名
 */
 private void saveXMLFile(Document document) {
    try {
     OutputFormat format = OutputFormat.createPrettyPrint();
     format.setEncoding("utf-8");
     XMLWriter writer = new XMLWriter(new FileWriter(new File(filePath)),format);
     writer.write(document);  
     writer.close();
    } catch (Exception e) {  
    // String loginfo = StackTraceToString.getExceptionTrace(e);
    // writelog.writeLogToEnd("LocalServerManager", loginfo);
    }
 }
 /**
 * 判斷XML文件是否存在.
 * @param fileName
 * @return
 */
 private boolean fileExist() {
    java.io.File objFile = new java.io.File(this.filePath);
    if (objFile.exists()) {
     return true;
    } else {
      return false;
  }
 }
}

XML文件:

復(fù)制代碼 代碼如下:

<?xml version="1.0" encoding="utf-8"?>


<style>

  <div id="div8">

    <module id="m1" name="module1" url="index1.jsp"/> 

   <module id="m2" name="module2" url="index2.jsp"/> 

    <module id="m3" name="module3" url="index3.jsp"/>

 </div>

  <div id="div9">

 
  <module id="m9" name="module9" url="index3.jsp"/>

  <module id="m10" name="module10" url="index4.jsp"/>

   <module id="m11" name="module11" url="index5.jsp"/>

 </div>

 </style>

解析:這里應(yīng)用遞歸的方式來(lái)判斷是對(duì)跟節(jié)點(diǎn)還是子節(jié)點(diǎn)的操作,相對(duì)比較清晰,這里用的是if判斷來(lái)判斷選擇的是那種操作,如果變動(dòng)相對(duì)較多,我感覺(jué)可以利用依賴注入,省去了if判斷的麻煩,但是當(dāng)時(shí)只是做了一個(gè)demo,沒(méi)有更多的優(yōu)化,如果有興趣的話可以試一試。
總結(jié):讀取XML其實(shí)并不難,在寫(xiě).NET系統(tǒng)的時(shí)候就寫(xiě)過(guò)關(guān)于xml的讀取,但是當(dāng)時(shí)真的就是一個(gè)一個(gè)的寫(xiě),需要什么在哪個(gè)方法下寫(xiě)什么,不僅要寫(xiě)很多重復(fù)的代碼,而且有一點(diǎn)問(wèn)題需要重復(fù)的修改,所以,有時(shí)候,雖然實(shí)現(xiàn)了需求重要,但是怎么實(shí)現(xiàn),同樣重要!

相關(guān)文章

  • 一文教會(huì)Java新手使用Spring?MVC中的查詢字符串和查詢參數(shù)

    一文教會(huì)Java新手使用Spring?MVC中的查詢字符串和查詢參數(shù)

    在使用springMVC框架構(gòu)建web應(yīng)用,客戶端常會(huì)請(qǐng)求字符串、整型、json等格式的數(shù)據(jù),這篇文章主要給大家介紹了關(guān)于通過(guò)一文教會(huì)Java新手使用Spring?MVC中的查詢字符串和查詢參數(shù)的相關(guān)資料,需要的朋友可以參考下
    2024-01-01
  • Java排序算法之堆排思想及代碼實(shí)現(xiàn)

    Java排序算法之堆排思想及代碼實(shí)現(xiàn)

    今天小編就為大家分享一篇關(guān)于Java排序算法之堆排思想及代碼實(shí)現(xiàn),小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-01-01
  • 解決@ConfigurationProperties注解的使用及亂碼問(wèn)題

    解決@ConfigurationProperties注解的使用及亂碼問(wèn)題

    這篇文章主要介紹了解決@ConfigurationProperties注解的使用及亂碼問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-10-10
  • java中的空指針異常情況以及解決方案

    java中的空指針異常情況以及解決方案

    這篇文章主要介紹了java中的空指針異常情況以及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • 一文詳解如何使用Java分割PDF文件

    一文詳解如何使用Java分割PDF文件

    PDF是一種用于顯示和打印文檔的文件格式,它非常廣泛地應(yīng)用于電子書(shū)籍、報(bào)告、合同等文件的傳遞和共享,這篇文章主要給大家介紹了關(guān)于如何使用Java分割PDF文件的相關(guān)資料,需要的朋友可以參考下
    2024-01-01
  • Javaweb請(qǐng)求轉(zhuǎn)發(fā)及重定向?qū)崿F(xiàn)詳解

    Javaweb請(qǐng)求轉(zhuǎn)發(fā)及重定向?qū)崿F(xiàn)詳解

    這篇文章主要介紹了Javaweb請(qǐng)求轉(zhuǎn)發(fā)及重定向?qū)崿F(xiàn)詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-07-07
  • @MapperScan注解與@Mapper注解的使用

    @MapperScan注解與@Mapper注解的使用

    這篇文章主要介紹了@MapperScan注解與@Mapper注解的使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • SpringBoot項(xiàng)目多數(shù)據(jù)源及mybatis 駝峰失效的問(wèn)題解決方法

    SpringBoot項(xiàng)目多數(shù)據(jù)源及mybatis 駝峰失效的問(wèn)題解決方法

    這篇文章主要介紹了SpringBoot項(xiàng)目多數(shù)據(jù)源及mybatis 駝峰失效的問(wèn)題解決方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-07-07
  • spring boot linux啟動(dòng)方式詳解

    spring boot linux啟動(dòng)方式詳解

    這篇文章主要介紹了spring boot linux啟動(dòng)方式詳解,分為為前臺(tái)啟動(dòng),后臺(tái)啟動(dòng)和腳本啟動(dòng)的各種方式講解,需要的朋友可以參考下
    2017-11-11
  • Mybatis中的mapper是如何和XMl關(guān)聯(lián)起來(lái)的

    Mybatis中的mapper是如何和XMl關(guān)聯(lián)起來(lái)的

    這篇文章主要介紹了Mybatis中的mapper是如何和XMl關(guān)聯(lián)起來(lái)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-06-06

最新評(píng)論