xml简单工具类
发布时间:2020-12-16 05:55:59 所属栏目:百科 来源:网络整理
导读:/* * 运用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();
}
}
}
} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
