常用的对xml文件进行读/存操作的工具类
public class XmlUtils {
private static String filename="user.xml";//user.xml文件放在src目录下
public static Document getDocument() throws DocumentException{
//用类加载器获取xml文件的绝对路径,可以看到文件与其他类一起被加载到了classes目录下
//url=file:/Users/xingxing/Workspaces/MyEclipse/day09_user/WebRoot/WEB-INF/classes/user.xml
URL url = XmlUtils.class.getClassLoader().getResource(filename);
//realpath=/Users/xingxing/Workspaces/MyEclipse/day09_user/WebRoot/WEB-INF/classes/user.xml
String realpath = url.getPath();
SAXReader reader = new SAXReader();
File file = new File(realpath);
Document document = reader.read(realpath);
return 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 FileWriter((new File(realpath))), format);
writer.write(document);
writer.close();
}
}