一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務(wù)器之家 - 編程語言 - JAVA教程 - java操作XML實(shí)例代碼

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

2019-11-04 14:15java教程網(wǎng) JAVA教程

這篇文章主要介紹了java操作XML實(shí)例代碼,有需要的朋友可以參考一下

最近一直在做高效平臺(tái)的框架,其實(shí)意識到我要做一個(gè)簡單的框架的時(shí)候是在我已經(jīng)做完我認(rèn)為的一版界面之后,開始以為我要做的是一個(gè)可配置的首頁展示,但是吭哧吭哧做了兩個(gè)星期,大概功能實(shí)現(xiàn)了之后,才發(fā)現(xiàn)要做的不是這個(gè),哎,需求不清楚害死人啊,但是這兩個(gè)星期并沒有白白浪費(fèi),也從中學(xué)到了很多東西,下面主要介紹讀取XML
在做系統(tǒng)的時(shí)候,經(jīng)常會(huì)遇到讀取xml的需求,一開始是讀取,于是我上網(wǎng)開始查詢讀取,接著查詢刪除,接著查詢修改,當(dāng)把這些代碼查的差不多的時(shí)候,我發(fā)現(xiàn),我為什么不把這些的操作都封裝到一個(gè)類里,使用的時(shí)候直接調(diào)用,豈不是更好,感覺之前腦袋都秀逗了,分別查了那么多,還一個(gè)個(gè)的調(diào)試,抱著這個(gè)心態(tài)繼續(xù)上網(wǎng)查(因?yàn)槲艺嫘母杏X網(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 {
     //寫日志
    // 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{
          //寫日志
          //  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)用遞歸的方式來判斷是對跟節(jié)點(diǎn)還是子節(jié)點(diǎn)的操作,相對比較清晰,這里用的是if判斷來判斷選擇的是那種操作,如果變動(dòng)相對較多,我感覺可以利用依賴注入,省去了if判斷的麻煩,但是當(dāng)時(shí)只是做了一個(gè)demo,沒有更多的優(yōu)化,如果有興趣的話可以試一試。
總結(jié):讀取XML其實(shí)并不難,在寫.NET系統(tǒng)的時(shí)候就寫過關(guān)于xml的讀取,但是當(dāng)時(shí)真的就是一個(gè)一個(gè)的寫,需要什么在哪個(gè)方法下寫什么,不僅要寫很多重復(fù)的代碼,而且有一點(diǎn)問題需要重復(fù)的修改,所以,有時(shí)候,雖然實(shí)現(xiàn)了需求重要,但是怎么實(shí)現(xiàn),同樣重要!

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 欧洲美女bbbxxxxxx | 日韩一级免费毛片 | 国产自拍视频一区 | 无遮挡激情 | 成人在线视频在线观看 | 国产真实一区二区三区 | 国产在线麻豆波多野结衣 | 国外成品精品1688 | 欧美一二区视频 | 女人zooxx禽交 | 久久视频在线视频观看精品15 | 亚飞与亚基高清国语在线观看 | 国产高清不卡视频在线播放 | 午夜国产小视频 | 白丝超短裙被输出娇喘不停小说 | 免费精品国产在线观看 | 99久久www免费 | 亚洲福利一区二区精品秒拍 | 护士被多人调教到失禁h | 色老板最新网站视频地址 | 日本中年japanesebear| 国产欧美综合一区二区 | chinese壮直男gay老年人 | 久久全国免费观看视频 | 国产裸舞福利资源在线视频 | 亚洲成人一区在线 | 国产一区二区三区毛片 | 视频一区久久 | 亚洲男人天堂影院 | a人片| 亚洲国产成人在线视频 | 视频一区在线免费观看 | 国产精品短视频 | 免费午夜影片在线观看影院 | 色漫在线观看 | 国产精品美女福利视频免费专区 | 猫咪免费人成网站在线观看入口 | 魔镜号中文字幕 | 性绞姿始动作动态图 | 人皮高跟鞋在线观看 | 91久久综合 |