也许我们在平常 进行web应用开发时,会经常同xml文档打交道,如通过xml文档进行配置相关信息等。下面就介绍一种常用的开源工具操作模式。也就是通过dom4j对xml文档的读取操作。
下面给出两个工具类:XmlDom4jUtil.java与Configure.java
-----XmlDom4jUtil.java
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
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 XmlDom4jUtil {
/**
* description:从XML文档到Document对象,如果XML文档不存在,则返回的Document对象为空。
* 解析.xml文件成一个 Document 对象
* @param filePath eg.xml文件所在路径或文件名
* @return
*/
public Document createDocXMLFile(String filePath){
Document document = null;
File file = new File(filePath);
if(file.exists()){
try{
SAXReader saxReader = new SAXReader();
document = saxReader.read(new File(filePath));
}catch(Exception ex){
ex.printStackTrace();
}
}
return document;
}
/**
* description:从Document对象到XML文档 如果Document为空或filePath为空,则返回更新失败false。
* 将经过处理的Document 对象转化为物理存储文件xml存放到filePath路径上
* @param document
* @param filePath 将要生成的xml文档存放到的路径
* @return
*/
public boolean updateXMLFileDoc(Document document,String filePath){
boolean result = false;
if(document==null||filePath==null){
return false;
}
try{
XMLWriter writer = null;
/** 格式化输出,类型IE浏览一样 */
OutputFormat format = OutputFormat.createPrettyPrint();
/** 指定XML编码 */
format.setEncoding("UTF-8");
//不要用 FileWriter 输出双字节,改为 FileOutputStream 输出单字节:
writer= new XMLWriter(new FileOutputStream(new File(filePath)),format);
writer.write(document);
writer.close();
/** 执行成功,需返回1 */
result = true;
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}
}
---Configure.java
import org.dom4j.Document;
import com.hymake.hyplat.app.util.AppClassUtil;
import com.hymake.hyplat.app.util.XmlDom4jUtil;
public class Configure {
private String filename ="";
public Configure(String fileName){
this.filename = fileName.trim();
}
//"//approval-config.xml"
/**
* 获得配置文件对应的Document对象
*/
public Document getCurrentDoc(){
XmlDom4jUtil xmlUtil = new XmlDom4jUtil();
String filePath = AppClassUtil.getClassRootPath(this.getClass())+"//"+filename;
Document doc = xmlUtil.createDocXMLFile(filePath);
return doc;
}
/**
* 获得配置文件在应用的绝对路径
* @return
*/
public String getAbsoluteFilePath(){
return AppClassUtil.getClassRootPath(this.getClass())+"//"+filename;
}
}