java操作XML实例代码
最近一直在做高效平台的框架,其实意识到我要做一个简单的框架的时候是在我已经做完我认为的一版界面之后,开始以为我要做的是一个可配置的首页展示,但是吭哧吭哧做了两个星期,大概功能实现了之后,才发现要做的不是这个,哎,需求不清楚害死人啊,但是这两个星期并没有白白浪费,也从中学到了很多东西,下面主要介绍读取xml。
在做系统的时候,经常会遇到读取xml的需求,一开始是读取,于是我上网开始查询读取,接着查询删除,接着查询修改,当把这些代码查的差不多的时候,我发现,我为什么不把这些的操作都封装到一个类里,使用的时候直接调用,岂不是更好,感觉之前脑袋都秀逗了,分别查了那么多,还一个个的调试,抱着这个心态继续上网查(因为我真心感觉网上肯定有,如果我自己封装的话脑袋就真的进水了)。
源代码展示:
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项目\\高校平台\\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();//获取根节点名称
}
public testadddeletexml(string filepath){
this.document = null;
this.filepath = filepath;
//writelog = new writelog();
}
/**
* 创建xml文件
* @param rootname:根节点名称
*/
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:父节点名称
* @param fatherattr:父节点属性
* @param childname:要添加的节点名称
* @param childvalue:要添加的节点值
*/
public void addchild(string fathernode, string fatherattr,string childname, string childvalue,map mapattr) {
childoperator(fathernode,fatherattr,childname,childvalue,"add",mapattr,0);
}
/**
* 修改元素
* @param fatherpath:父节点名称
* @param fatherattr:父节点属性
* @param childname:要修改的节点名称
* @param childvalue:要修改成的节点值
*/
public void updatechild(string fathernode, string fatherattr,string childname, string childvalue,int updatid) {
childoperator(fathernode,fatherattr,childname,childvalue,"update",null,updatid);
}
/**
* 删除元素
* @param fatherpath:父节点名称
* @param fatherattr:父节点属性
* @param childname:要删除的节点名称
*/
public void deletechild(string fathernode, string fatherattr,string childname) {
childoperator(fathernode,fatherattr,childname,"","delete",null,0);
}
/**
* 删除元素
* @param fatherpath:父节点名称
* @param fatherattr:父节点属性
* @param childname:要删除的节点名称
*/
public void deletechildall(string fathernode, string fatherattr,string childname) {
childoperator(fathernode,fatherattr,childname,"","deleteall",null,0);
}
/**
* 删除某个元素
* @param fatherpath:父节点名称
* @param fatherattr:父节点属性
* @param childname:要删除的节点名称
*/
public void deletechildone(string fathernode, string fatherattr,string childname,string childvalue) {
childoperator(fathernode,fatherattr,childname,childvalue,"deleteone",null,0);
}
/**
* 获取某个元素数值
* @param fatherpath:父节点名称
* @param fatherattr:父节点属性
* @param childname:要删除的节点名称
*/
public string getchild(string fathernode, string fatherattr,string childname) {
string result = "";
result = childoperator(fathernode,fatherattr,childname,"","get",null,0);
return result;
}
/**
* 子节点操作
* @param fathernode:父节点名称
* @param fatherattr:父节点属性
* @param childname:要修改的节点
* @param childvalue:修改后的节点值
* @param operator: 要执行的操作名称
*/
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();//获取根节点名称
if(!root.getname().equals(fathernode)){ //如果不是在根节点下添加
result = xmlelementoperator(root,fathernode,fatherattr,childname,childvalue,operator,mapattr);
}else{
if(operator.equals("add")){
element childelement = root.addelement(childname);//根节点不存在元素属性值
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);//获取当前节点下的所有子节点,判断其值,以进行修改
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);//获取当前节点下的所有子节点,判断其值,以进行修改
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);//获取当前节点下的所有子节点,判断其值,以进行修改
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();//获取当前节点下的所有子节点,判断其值,以进行修改
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:父节点名称
* @param fatherattr:父节点属性
* @param childname:要进行操作的节点
* @param childvalue:操作后的节点值
* @param operator: 要执行的操作名称
*/
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)){ //当前元素并不是我们要查找的父元素时,继续查找
xmlelementoperator(currentelement,fathernode,fatherattr,childname,childvalue,operator,mapattr);//递归调用
}else{
if(currentelement.attributecount()>0){ //当前元素存在属性值时
for(iterator list=currentelement.attributeiterator();list.hasnext();){ //遍历属性值
attribute attr = (attribute)list.next(); //获取属性值队列中的第一个元素
if(attr.getvalue().equals(fatherattr)){//根据属性值确定惟一的父元素
if(operator.equals("add")){//添加元素
element childelement = currentelement.addelement(childname); //给当前元素添加一个子元素
childelement.settext(childvalue); //设置子元素的数值
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);//获取当前节点下的所有子节点,判断其值,以进行修改
for(iterator childs=childelements.iterator();childs.hasnext();){
element everyone = (element)childs.next();
everyone.settext(childvalue); //修改该元素值
}
}else if(operator.equals("delete")){ //删除某个指定的元素
list childelements = currentelement.elements();//获取当前节点下的所有子节点,判断其值,以进行修改
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);//获取当前节点下的所有子节点,判断其值,以进行修改
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文件:
<?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>
解析:这里应用递归的方式来判断是对跟节点还是子节点的操作,相对比较清晰,这里用的是if判断来判断选择的是那种操作,如果变动相对较多,我感觉可以利用依赖注入,省去了if判断的麻烦,但是当时只是做了一个demo,没有更多的优化,如果有兴趣的话可以试一试。
总结:读取xml其实并不难,在写.net系统的时候就写过关于xml的读取,但是当时真的就是一个一个的写,需要什么在哪个方法下写什么,不仅要写很多重复的代码,而且有一点问题需要重复的修改,所以,有时候,虽然实现了需求重要,但是怎么实现,同样重要!