操作XML文件工具类

       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;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值