xml文件是java开发中必不可少的东西,因此有必要熟悉xml文件的操作,编写一个xml文件工具类,供以后翻阅查看,温故而知新,好记性不如烂笔头。
代码如下:
public class Dom4jUtil {
private Dom4jUtil(){}
/**
* 创建文档对象
* @return
*/
public static Document createDocument()
{
Document document = DocumentHelper.createDocument();
return document;
}
/**
* 获得文档对象
* @param filePath 文件路径
* @return
* @throws DocumentException
* @throws FileNotFoundException
*/
public static Document getDocument(String filePath) throws DocumentException, FileNotFoundException
{
try
{
SAXReader saxReader = new SAXReader();
//文件是否存在
File file = new File(filePath);
if(file.exists())
{
Document document = saxReader.read(new File(filePath));
return document;
}
else
{
throw new FileNotFoundException(filePath+"文件未找到");
}
}
catch(DocumentException ex)
{
throw new DocumentException("解析xml错误", ex);
}
}
/**
* 创建根元素
* @param document 文档对象
* @param rootName 根元素名
* @return
*/
public static Element createRoot(Document document, String rootName)
{
Element root = document.addElement(rootName);
return root;
}
/**
* 创建元素节点
* @param parentEle 父节点
* @param eleName 元素名
* @param attrMap 元素属性信息
* @param text 元素文本
* @return
*/
public static Element createElement(Element parentEle, String eleName, Map<String, String> attrMap, String text)
{
//添加元素节点
Element element = parentEle.addElement(eleName);
//如果有属性信息
if(attrMap != null && attrMap.size() > 0)
{
for(Iterator<String> it = attrMap.keySet().iterator(); it.hasNext();)
{
String attr_key = it.next();
String attr_value = attrMap.get(attr_key);
element.addAttribute(attr_key, attr_value);
}
}
//添加文本信息
if(text != null && !"".equals(text))
{
element.addText(text);
}
return parentEle;
}
/**
* 写入XML
* @param xmlPath xml路径
* @param document 文档对象
* @return 写入结果
* @throws IOException
*/
public static boolean write(String xmlPath, Document document) throws IOException
{
try
{
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(xmlPath),"UTF-8"); //中文处理
XMLWriter xmlWriter= new XMLWriter(osw,format);
xmlWriter.write(document);
xmlWriter.close();
}
catch(IOException ex)
{
throw new IOException("写入xml错误", ex);
}
return true;
}
}