通过JDOM写XML文件

public void writeXMLByJDOM()
    {
        Element rootElement = new Element("users");  //创建以users为name的根节点
        
        Element secondElement = new Element("user");  //创建以user为name的第二层节点
        secondElement.setAttribute("name", "name1");  //给第二层节点添加name为"name",value为"name1"的属性
        
        rootElement.addContent(secondElement); //将第二层节点添加到根节点下
        
        Element thirdElement = new Element("age");  //创建name为"age"的第三层节点
        thirdElement.setText("18");  //输入第三层节点的值为18
        secondElement.addContent(thirdElement);  //将第三层节点添加到第二层节点下
        
        thirdElement = new Element("gender");  //重新创建一个name为"gender"的第三层节点
        thirdElement.setText("w");  //输入第三层节点的值为"w"
        secondElement.addContent(thirdElement);  //将新创建的第三层节点再次添加到第二层节点下
        

        thirdElement = new Element("address");  //重新创建一个name为"address"的第三层节点
        thirdElement.setText("addresss");  //输入第三层节点的值为"addresss"
        secondElement.addContent(thirdElement);  //将新创建的第三层节点再次添加到第二层节点下
        
        String xmlFilePath = System.getProperty("user.dir")
        + File.separator + "config" + File.separator + "test.xml";
        
        Document writeDoc = new Document(rootElement);
        
        XMLOutputter XMLOut = new XMLOutputter();
        Format format = Format.getPrettyFormat(); // 格式化文档
        format.setEncoding("UTF-8"); // 设置编码格式为utf-8
        XMLOut.setFormat(format);
        try
        {
            XMLOut.output(writeDoc, new FileOutputStream((xmlFilePath).trim()));
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值