1 //dom4j添加内容,在第一本书上指定位置添加售价 更改保存所有孩子list集合的顺序 2 @Test 3 public void add1() throws Exception{ 4 //读 5 SAXReader reader = new SAXReader(); 6 Document document = reader.read(new File("src/book.xml")); 7 8 //添加 9 Element book = document.getRootElement().element("书"); 10 List list = book.elements();//[书名、作者、售价] 11 Element price = DocumentHelper.createElement("售价"); 12 price.setText("309"); 13 list.add(2,price); 14 15 //输出 16 OutputFormat format = OutputFormat.createPrettyPrint(); 17 format.setEncoding("UTF-8"); 18 XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),format); 19 writer.write(document); 20 writer.close(); 21 22 } 23 @Test 24 public void deleat() throws Exception{ 25 //读 26 SAXReader reader = new SAXReader(); 27 Document document = reader.read(new File("src/book.xml")); 28 29 //删除 30 Element price = document.getRootElement().element("书").element("售价"); 31 price.getParent().remove(price); 32 33 //输出 34 OutputFormat format = OutputFormat.createPrettyPrint(); 35 format.setEncoding("UTF-8"); 36 XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),format); 37 writer.write(document); 38 writer.close(); 39 40 }