欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用dom4j读写XML

程序员文章站 2022-01-03 10:04:33
...


/**
* 获取Dom4j的Document对象, 默认字符集UTF-8
* @param data
* @return
* @throws ParseException
*/
public static Document getDocument(String data) throws ParseException{

return getDocument(data, "UTF-8");

}

/**
* 获取Dom4j的Document对象
* @param data
* @param charset
* @return
*/
public static Document getDocument(String data, String charset) throws ParseException{

SAXReader reader = new SAXReader();
Document document = null;
InputStreamReader utfreader = null;
InputStream in = null;

try {
in = new ByteArrayInputStream(data.getBytes());
utfreader = new InputStreamReader(in, charset);
document = reader.read(utfreader);
}
catch (DocumentException e) {
throw new ParseException(e.getMessage(), e);
}
catch(UnsupportedEncodingException e){
throw new ParseException(e.getMessage(), e);
}
finally {
try {
in.close();
}
catch (IOException e) {
}
}
return document;
}

/**
* 将XML数据流备份成文件
* @param data
* @param saveFilePath
* @param saveFileName
* @return
*/
public boolean saveFile(String data, String saveFilePath, String saveFileName){

File file = new File(saveFilePath);
if(!file.exists()){
file.mkdirs();
}

String filePath = saveFilePath + File.separator + saveFileName;

boolean success = false;

Writer writer = null;
XMLWriter xmlWriter = null;
SAXReader reader = new SAXReader();
Document document = null;
InputStreamReader utfreader = null;
InputStream in = null;

try {
in = new ByteArrayInputStream(data.getBytes());
utfreader = new InputStreamReader(in, "UTF-8");
document = reader.read(utfreader);

writer = new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
xmlWriter = new XMLWriter(writer, format);
xmlWriter.write(document);
xmlWriter.flush();
success = true;
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
log.error(e);
}
catch (FileNotFoundException e) {
e.printStackTrace();
log.error(e);
}
catch (DocumentException e) {
e.printStackTrace();
log.error(e);
}
catch (IOException e) {
e.printStackTrace();
log.error(e);
}
finally{
try {
utfreader.close();
writer.close();
}catch (IOException e) {}
}
return success;
}

相关标签: XML