packageutil;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.FileWriter;importjava.io.StringReader;importorg.jdom.Document;importorg.jdom.input.SAXBuilder;importorg.jdom.output.Format;importorg.jdom.output.XMLOutputter;/*** JDOM 方式操作XML
*
*@authorWatson Xu
* @date 2011-5-3 下午02:20:49*/
public classOperationXMLByJdom {/*** DOCUMENT格式化输出保存为XML
*
*@paramdoc JDOM的Document
*@paramfilePath 输出文件路径
*@throwsException*/
public static void doc2XML(Document doc, String filePath) throwsException{
Format format=Format.getCompactFormat();
format.setEncoding("UTF-8"); //设置XML文件的字符为UTF-8
format.setIndent(" ");//设置缩进
XMLOutputter outputter= new XMLOutputter(format);//定义输出 ,在元素后换行,每一层元素缩排四格
FileWriter writer = new FileWriter(filePath);//输出流
outputter.output(doc, writer);
writer.close();
}/*** 字符串转换为DOCUMENT
*
*@paramxmlStr 字符串
*@returndoc JDOM的Document
*@throwsException*/
public static Document string2Doc(String xmlStr) throwsException {
java.io.Reader in= newStringReader(xmlStr);
Document doc= (newSAXBuilder()).build(in);returndoc;
}/*** Document转换为字符串
*
*@paramxmlFilePath XML文件路径
*@returnxmlStr 字符串
*@throwsException*/
public static String doc2String(Document doc) throwsException {
Format format=Format.getPrettyFormat();
format.setEncoding("UTF-8");//设置xml文件的字符为UTF-8,解决中文问题
XMLOutputter xmlout = newXMLOutputter(format);
ByteArrayOutputStream bo= newByteArrayOutputStream();
xmlout.output(doc, bo);returnbo.toString();
}/*** XML转换为Document
*
*@paramxmlFilePath XML文件路径
*@returndoc Document对象
*@throwsException*/
public static Document xml2Doc(String xmlFilePath) throwsException {
File file= newFile(xmlFilePath);return (newSAXBuilder()).build(file);
}public static voidmain(String[] args) {try{
Document doc= xml2Doc("test.xml");
System.out.println(doc);
System.out.println(doc2String(doc));
doc=string2Doc(doc2String(doc));
doc2XML(doc,"1.xml");
}catch(Exception e) {
e.printStackTrace();
}
}
}