加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xml简单工具类

发布时间:2020-12-16 08:43:14 所属栏目:百科 来源:网络整理
导读:/* * 运用Dom4j实现一个简单的工具类 */public class XMLUtils { private XMLUtils(){}//获取文档对象public static Document getDocument(File file) {Document doc = null;SAXReader sax = new SAXReader();try {doc = sax.read(file);} catch (DocumentEx
/*
 * 运用Dom4j实现一个简单的工具类
 */
public class XMLUtils {
   
	private XMLUtils(){}
	//获取文档对象
	public static Document getDocument(File file) {
		Document doc = null;
		SAXReader sax = new SAXReader();
		try {
			doc = sax.read(file);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return doc;
	}
	
	//写入文档
	public static void writerToXml(Document doc,File file) {
		OutputFormat opf = OutputFormat.createPrettyPrint(); // 排版格式
		opf.setEncoding("utf-8");
		// OutputFormat opf=OutputFormat.createCompactFormat();//紧凑格式
		// 写入所需要的xml文件
		OutputStream os=null;
		XMLWriter xmlWriter=null;
		try{
		    os= new FileOutputStream(file);
			// 创建一个XMLWriter对象
		    xmlWriter = new XMLWriter(os,opf);
			//写出到目标文件
			xmlWriter.write(doc);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			//手动关闭流
			try {
				xmlWriter.close();
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读