dom4j---two
//在第一本书的第三个位置加一个价钱 @Test public void test1() throws DocumentException, Exception{ SAXReader read=new SAXReader(); Document document=read.read("src/Demo2.xml"); Element root=document.getRootElement(); List list=root.element("书").elements(); Element price=DocumentHelper.createElement("价钱"); price.setText("998元"); list.add(2,price); OutputFormat format = OutputFormat.createPrettyPrint();//格式化输入器 format.setEncoding("UTF-8");//设置格式化输入的编码 XMLWriter writer = new XMLWriter(new FileOutputStream("src/Demo2.xml"),format); writer.write(document); writer.close(); } /*删除第三个价钱 *<书> <书名>什么都不知道</书名> <作者>某及</作者> <价钱>100</价钱> <价钱>100元</价钱> <价钱>998</价钱> <价钱>98</价钱> </书> * */ @Test public void test2() throws Exception{ SAXReader read=new SAXReader(); Document document=read.read("src/Demo2.xml"); Element root=document.getRootElement(); Element price=(Element)root.element("书").elements("价钱").get(2); if(price.getParent().remove(price)){ System.out.println("删除成功"); } OutputFormat format=new OutputFormat(); format.setEncoding("UTF-8"); XMLWriter write=new XMLWriter(new FileOutputStream("src/Demo2.xml"),format); write.write(document); write.close(); } @Test public void test3() throws Exception{ SAXReader read=new SAXReader(); Document document=read.read("src/Demo2.xml"); Element root=document.getRootElement(); Element book_2=(Element)root.elements("书").get(1); book_2.element("价钱").setText("无价之宝"); OutputFormat format=new OutputFormat(); format.setEncoding("UTF-8"); XMLWriter write=new XMLWriter(new FileOutputStream("src/Demo2.xml"),format); write.write(document); write.close(); }
现在的几乎什么都不懂,但是不代表以后的我也是这样。