dom4j操作XML
public class XmlUtils {
private static String filename = "users.xml";//模拟数据库
public static Document getDocument() throws DocumentException{
URL url = XmlUtils.class.getClassLoader().getResource(filename);
String realpath = url.getPath();
SAXReader reader = new SAXReader();
return reader.read(new File(realpath));//返回Document对象
}
public static void write2Xml(Document document) throws IOException{
URL url = XmlUtils.class.getClassLoader().getResource(filename);
String realpath = url.getPath();
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(new FileOutputStream(realpath), format );
writer.write( document );//向Document对象中写入数据
writer.close();
}
}