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

 

转载于:https://www.cnblogs.com/08love125/articles/5436702.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值