亚洲AV日韩AⅤ综合手机在线观看,激情婷婷久久综合色,欧美色五月婷婷久久,久久国产精品99久久人人澡

  • <abbr id="uk6uq"><abbr id="uk6uq"></abbr></abbr>
  • <tbody id="uk6uq"></tbody>
  • java操作xml的一個(gè)小例子

    時(shí)間:2020-11-09 17:29:56 XML 我要投稿

    java操作xml的一個(gè)小例子

      最近一直在做高效平臺(tái)的框架,其實(shí)意識(shí)到我要做一個(gè)簡(jiǎn)單的框架的時(shí)候是在我已經(jīng)做完我認(rèn)為的一版界面之后,開始以為我要做的是一個(gè)可配置的首頁(yè)展示,但是吭哧吭哧做了兩個(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)demogxptWebContentlimitsmanager.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.ChildOne("style", "","div","div11");

      //operator.Child("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 Child(String fatherNode, String fatherAttr,String childName) {

      ChildOperator(fatherNode,fatherAttr,childName,"","",null,0);

      }

      /**

      * 刪除元素

      * @param fatherPath:父節(jié)點(diǎn)名稱

      * @param fatherattr:父節(jié)點(diǎn)屬性

      * @param childName:要?jiǎng)h除的節(jié)點(diǎn)名稱

      */

      public void ChildAll(String fatherNode, String fatherAttr,String childName) {

      ChildOperator(fatherNode,fatherAttr,childName,"","All",null,0);

      }

      /**

      * 刪除某個(gè)元素

      * @param fatherPath:父節(jié)點(diǎn)名稱

      * @param fatherattr:父節(jié)點(diǎn)屬性

      * @param childName:要?jiǎng)h除的節(jié)點(diǎn)名稱

      */

      public void ChildOne(String fatherNode, String fatherAttr,String childName,String childValue) {

      ChildOperator(fatherNode,fatherAttr,childName,childValue,"One",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("")){

      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("One")){

      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("All")){

      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("")){ //刪除某個(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ù)制代碼 代碼如下:

      解析:這里應(yīng)用遞歸的方式來判斷是對(duì)跟節(jié)點(diǎn)還是子節(jié)點(diǎn)的操作,相對(duì)比較清晰,這里用的是if判斷來判斷選擇的是那種操作,如果變動(dòng)相對(duì)較多,我感覺可以利用依賴注入,省去了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),同樣重要!

    【java操作xml的一個(gè)小例子】相關(guān)文章:

    1.關(guān)于JAVA的XML編程

    2.Java讀取xml文件的方法

    3.XML入門操作程序

    4.用Java如何處理XML數(shù)據(jù)

    5.Java中如何構(gòu)造、生成XML簡(jiǎn)明

    6.java關(guān)于多線程的操作

    7.JAVA IO操作知識(shí)匯總

    8.Java數(shù)組操作方法大全