XML文件格式:
<?xml version="1.0" encoding="UTF-8"?> <company> <employee name="zhangsan" value="张三"/> <employee name="lisi" value="李四"/> <employee name="wangwu" value="王五"/> </company>
dom4j读写方法:
/** * 读取 */ public static void read() { try { File xmlFile = new File("d://company.xml"); Document document = new SAXReader().read(xmlFile); List<Element> elements = document.selectNodes("/company/employee"); for (Element element : elements) { String name = element.attributeValue("name"); String value = element.attributeValue("value"); System.out.println(name + " = " + value); } } catch (Exception e) { e.printStackTrace(); } } /** * 写入 */ public static void write() { FileOutputStream fileOutputStream = null; XMLWriter xmlWriter = null; try { File xmlFile = new File("d://company.xml"); Document document = new SAXReader().read(xmlFile); // 获取根节点 Element root = document.getRootElement(); // 动态添加 <employee name="xiaohong" value="小红"/> Element employee = root.addElement("employee"); employee.addAttribute("name", "xiaohong"); employee.addAttribute("value", "小红"); OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setEncoding("UTF-8"); outputFormat.setIndent(true); outputFormat.setIndent(" ");// tab格 outputFormat.setNewlines(true);// 换行 fileOutputStream = new FileOutputStream(xmlFile); xmlWriter = new XMLWriter(fileOutputStream, outputFormat); xmlWriter.write(document); } catch (Exception e) { e.printStackTrace(); } finally { if (xmlWriter != null) { try { xmlWriter.close(); } catch (IOException e) { } } } }
写入后XML格式:
<?xml version="1.0" encoding="UTF-8"?> <company> <employee name="zhangsan" value="张三"/> <employee name="lisi" value="李四"/> <employee name="wangwu" value="王五"/> <employee name="xiaohong" value="小红"/> </company>
注:所需包 dom4j-1.6.1.jar、jaxen-1.1.1.jar
时间: 2024-10-03 14:45:12