。。。。。。。。。
import org.jdom.Document;
import org.jdom.Element;
。。。。。。。。。。。。。。。。。。。。。。
public class XmlUtil {
/**
* 打开XML文件。
* @param fileName 文件名称。
* @return XML Document对象。
* @throws FileNotFoundException
*/
public static Document OpenDocument(String fileName){
SAXBuilder builder = new SAXBuilder();
Document doc = null;
try {
doc = builder.build(new File(fileName));
} catch (JDOMException e) {
log.error("解析文件错误[" + fileName + "]");
log.error(e);
} catch (IOException e) {
log.error("打开文件错误[" + fileName + "]");
log.error(e);
}
return doc;
}
/**
* 保存XML文档
* @param doc 要保存的文档
* @param fileName 文件名
* @param encoding 编码,比如"GB2312","UTF-8";
* @return 是否保存成功。
*/
public static boolean SaveDocument(Document doc,String fileName,String encoding)
{
boolean saveOK = false;
Format format = Format.getPrettyFormat();
format.setEncoding(encoding);
format.setOmitDeclaration(false);
XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(format);
try {
outputter.output(doc, new FileWriter(fileName));
saveOK = true;
} catch (IOException e) {
log.error("保存文件错误[" + fileName + "]");
log.error(e);
}
return saveOK;
}
JDOM的用法。