java操作xml的一個小例子
最近一直在做高效平臺的框架,其實意識到我要做一個簡單的框架的時候是在我已經(jīng)做完我認為的一版界面之后,開始以為我要做的是一個可配置的首頁展示,但是吭哧吭哧做了兩個星期,大概功能實現(xiàn)了之后,才發(fā)現(xiàn)要做的不是這個,哎,需求不清楚害死人啊,但是這兩個星期并沒有白白浪費,也從中學到了很多東西,下面主要介紹讀取XML。
在做系統(tǒng)的時候,經(jīng)常會遇到讀取xml的需求,一開始是讀取,于是我上網(wǎng)開始查詢讀取,接著查詢刪除,接著查詢修改,當把這些代碼查的差不多的時候,我發(fā)現(xiàn),我為什么不把這些的`操作都封裝到一個類里,使用的時候直接調(diào)用,豈不是更好,感覺之前腦袋都秀逗了,分別查了那么多,還一個個的調(diào)試,抱著這個心態(tài)繼續(xù)上網(wǎng)查(因為我真心感覺網(wǎng)上肯定有,如果我自己封裝的話腦袋就真的進水了)。
源代碼展示:
復制代碼 代碼如下:
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; //文件所在的實際物理路徑
//private WriteLog writelog;
public static void main(String[] args) throws DocumentException {
//String filepath = System.getProperty("user.dir")+"/XmlFiles/LocalServicesConfig.xml";
String filepath ="F:JAVA項目高校平臺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é)點名稱
}
public testAddDeleteXML(String filepath){
this.document = null;
this.filePath = filepath;
//writelog = new WriteLog();
}
/**
* 創(chuàng)建XML文件
* @param rootName:根節(jié)點名稱
*/
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é)點名稱
* @param fatherattr:父節(jié)點屬性
* @param childName:要添加的節(jié)點名稱
* @param childValue:要添加的節(jié)點值
*/
public void addChild(String fatherNode, String fatherAttr,String childName, String childValue,Map mapAttr) {
ChildOperator(fatherNode,fatherAttr,childName,childValue,"add",mapAttr,0);
}
/**
* 修改元素
* @param fatherPath:父節(jié)點名稱
* @param fatherattr:父節(jié)點屬性
* @param childName:要修改的節(jié)點名稱
* @param childValue:要修改成的節(jié)點值
*/
public void updateChild(String fatherNode, String fatherAttr,String childName, String childValue,int updatId) {
ChildOperator(fatherNode,fatherAttr,childName,childValue,"update",null,updatId);
}
/**
* 刪除元素
* @param fatherPath:父節(jié)點名稱
* @param fatherattr:父節(jié)點屬性
* @param childName:要刪除的節(jié)點名稱
*/
public void Child(String fatherNode, String fatherAttr,String childName) {
ChildOperator(fatherNode,fatherAttr,childName,"","",null,0);
}
/**
* 刪除元素
* @param fatherPath:父節(jié)點名稱
* @param fatherattr:父節(jié)點屬性
* @param childName:要刪除的節(jié)點名稱
*/
public void ChildAll(String fatherNode, String fatherAttr,String childName) {
ChildOperator(fatherNode,fatherAttr,childName,"","All",null,0);
}
/**
* 刪除某個元素
* @param fatherPath:父節(jié)點名稱
* @param fatherattr:父節(jié)點屬性
* @param childName:要刪除的節(jié)點名稱
*/
public void ChildOne(String fatherNode, String fatherAttr,String childName,String childValue) {
ChildOperator(fatherNode,fatherAttr,childName,childValue,"One",null,0);
}
/**
* 獲取某個元素數(shù)值
* @param fatherPath:父節(jié)點名稱
* @param fatherattr:父節(jié)點屬性
* @param childName:要刪除的節(jié)點名稱
*/
public String getChild(String fatherNode, String fatherAttr,String childName) {
String result = "";
result = ChildOperator(fatherNode,fatherAttr,childName,"","get",null,0);
return result;
}
/**
* 子節(jié)點操作
* @param fatherNode:父節(jié)點名稱
* @param fatherAttr:父節(jié)點屬性
* @param childName:要修改的節(jié)點
* @param childValue:修改后的節(jié)點值
* @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é)點名稱
if(!root.getName().equals(fatherNode)){ //如果不是在根節(jié)點下添加
result = XmlElementOperator(root,fatherNode,fatherAttr,childName,childValue,operator,mapAttr);
}else{
if(operator.equals("add")){
Element childelement = root.addElement(childName);//根節(jié)點不存在元素屬性值
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);//獲取當前節(jié)點下的所有子節(jié)點,判斷其值,以進行修改
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);//獲取當前節(jié)點下的所有子節(jié)點,判斷其值,以進行修改
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);//獲取當前節(jié)點下的所有子節(jié)點,判斷其值,以進行修改
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();//獲取當前節(jié)點下的所有子節(jié)點,判斷其值,以進行修改
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é)點名稱
* @param fatherAttr:父節(jié)點屬性
* @param childName:要進行操作的節(jié)點
* @param childValue:操作后的節(jié)點值
* @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)){ //當前元素并不是我們要查找的父元素時,繼續(xù)查找
XmlElementOperator(currentelement,fatherNode,fatherAttr,childName,childValue,operator,mapAttr);//遞歸調(diào)用
}else{
if(currentelement.attributeCount()>0){ //當前元素存在屬性值時
for(Iterator list=currentelement.attributeIterator();list.hasNext();){ //遍歷屬性值
Attribute attr = (Attribute)list.next(); //獲取屬性值隊列中的第一個元素
if(attr.getValue().equals(fatherAttr)){//根據(jù)屬性值確定惟一的父元素
if(operator.equals("add")){//添加元素
Element childelement = currentelement.addElement(childName); //給當前元素添加一個子元素
childelement.setText(childValue); //設置子元素的數(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")){//修改某個元素
List childelements = currentelement.elements(childName);//獲取當前節(jié)點下的所有子節(jié)點,判斷其值,以進行修改
for(Iterator childs=childelements.iterator();childs.hasNext();){
Element everyone = (Element)childs.next();
everyone.setText(childValue); //修改該元素值
}
}else if(operator.equals("")){ //刪除某個指定的元素
List childelements = currentelement.elements();//獲取當前節(jié)點下的所有子節(jié)點,判斷其值,以進行修改
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);//獲取當前節(jié)點下的所有子節(jié)點,判斷其值,以進行修改
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文件:
復制代碼 代碼如下:
解析:這里應用遞歸的方式來判斷是對跟節(jié)點還是子節(jié)點的操作,相對比較清晰,這里用的是if判斷來判斷選擇的是那種操作,如果變動相對較多,我感覺可以利用依賴注入,省去了if判斷的麻煩,但是當時只是做了一個demo,沒有更多的優(yōu)化,如果有興趣的話可以試一試。
總結:讀取XML其實并不難,在寫.NET系統(tǒng)的時候就寫過關于xml的讀取,但是當時真的就是一個一個的寫,需要什么在哪個方法下寫什么,不僅要寫很多重復的代碼,而且有一點問題需要重復的修改,所以,有時候,雖然實現(xiàn)了需求重要,但是怎么實現(xiàn),同樣重要!
【java操作xml的一個小例子】相關文章: