// Add content to XML @Test public void add() throws DocumentException, IOException { SAXReader reader = new SAXReader(); Document document = reader.read("src/book.xml"); Element book = document.getRootElement().element("book"); book.addElement("price").setText("199.0"); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter("src/book.xml"),format); writer.write(document); writer.close(); }
// Add content to XML in specific position @Test public void add2() throws DocumentException, IOException { SAXReader reader = new SAXReader(); Document document = reader.read("src/book.xml"); Element book = document.getRootElement().element("book"); List list = book.elements(); // [book, name, price] Element author = DocumentHelper.createElement("author"); author.setText("Ryan"); list.add(1, author); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter("src/book.xml"),format); writer.write(document); writer.close(); }
Update
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
@Test public void update() throws DocumentException, IOException { SAXReader reader = new SAXReader(); Document document = reader.read("src/book.xml"); Element author = document.getRootElement().element("book").element("author"); author.setText("Ryan Luo"); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter("src/book.xml"),format); writer.write(document); writer.close(); }