反射+jdom+xml例子,经过一番折腾,总算知道反射是啥意思了,真的很感谢帮助我的人,不知道说啥好了,就是感动,我把我做的东西和大家分
建一个文件夹D:\some\directory
Xml类
package com.cyberobject.study;
import java.io.File;
import java.io.FileWriter;
import
java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class Xml {
/**
* 向指定的xml文件写数据
* @param FileName 要用到的cell文件模板名
* @param dto 传输数据对象
* @throws
ClassNotFoundException * @throws
IllegalAccessException * @throws
IllegalArgumentException * @throws
InstantiationException */
public void writeXmlFile(DataTransaction dto) throws Class
NotFoundException, IllegalArgumentException, IllegalAccessException, InstantiationException{
Element rootElement = new Element( "WorkBook ");
Document myDocument = new Document(rootElement);
List dtoObjects = dto.getDtoObjects();
for(int i = 0 ; i < dtoObjects.size() ; i++){
Element cellFileElement = new Element( "CellFile ");
rootElement.addContent(cellFileElement);
DtoObject dtoObject = (DtoObject)dtoObjects.get(i);
cellFileElement.setAttribute( "name ",dtoObject.getCellFileName()+ ".cell ");
List objects = dtoObject.getObjects();
for(int j = 0 ;j < objects.size(); j++ ){
Object object = dtoObject.getObjects().get(j);
Element objElement = new Element( "Object ");
Field fieldList[] = object.getClass().getFields();
for(int k = 0 ; k < fieldList.length ; k++){
String fieldName = fieldList[k].getName().toString();
String fieldValue = fieldList[k].get(object).toString();
System.out.print(fieldName+ ": "+fieldValue);
objElement.setAttribute(fieldName,fieldValue.toString());
}
cellFileElement.addContent(objElement);
}
XMLOutputter output = new XMLOutputter(Format.getPrettyFormat());
try{
File mydir=new File( "d:/some/directory/ "+dto.getXmlFileName()+ ".xml ");
if(!mydir.exists()){
this.createFile( "d:/some/directory/ ",dto.getXmlFileName());
}else{
this.deleteFile( "d:/some/directory/ "+dto.getXmlFileName()+ ".xml ");
FileWriter fileWriter = new FileWriter( "d:/some/directory/ "+dto.getXmlFileName()+ ".xml ");
output.output(myDocument,fileWriter);
fileWriter.close();
}
}catch(
IOException e){
e.printStackTrace();
}
}
}
/**
* 删除文件