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();
    }

 

posted @ 2016-04-26 21:20  戒。  阅读(83)  评论(0编辑  收藏  举报