dom4j创建xml文件实例

package com.cn;

import java.io.File;
import java.io.FileOutputStream;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;

import org.dom4j.io.XMLWriter;

/**
 * 创建xml文件夹类
 * 创建者    : xxx
 * 创建日期: 2018年06月29日
 * */

public class CreateXml {

    /**
 * 例:创建Main.xml文件
 * 创建者    : xxx
 * 创建日期: 2018年06月12日
 * @version: 1.0 

 */

     public static boolean createMainXml() throws Exception { 

File xmlfile = null;  
    try {  
    xmlfile = new File("/Files/2c08acd6a61e472db47d8a1bb33c4776.txt");//具体文件路径  
         if (!xmlfile.exists()) {  
         Document doc = DocumentHelper.createDocument();
     
             //增加根节点
             Element fileRoot = doc.addElement("FileRoot");
             //增加子节点
             Element metadata = fileRoot.addElement("Metadata");
             Element docBody = fileRoot.addElement("DocBody");
             Element component = docBody.addElement("Component");
             Element file=component.addElement("File");
             Element FileLoc =file.addElement("FileLoc");
                  
             //节点增加属性
             fileRoot.addAttribute("type", "wenjian.tongyong");
             fileRoot.addAttribute("target", "ofd");
             component.addAttribute("id", "0");
             file.addAttribute("Title", "标题");
             file.addAttribute("Format", "doc");//需要传文件格式参数
             
             //节点增加值
             metadata.setText("Meta.xml");
             FileLoc.setText("/Files/2c08acd6a61e472db47d8a1bb33c4776.txt");//需要传文件路径参数
             
             //实例化输出格式对象
             OutputFormat format = OutputFormat.createPrettyPrint();
             //设置输出编码
             format.setEncoding("UTF-8");
             //创建需要写入的File对象
             File files = new File("E:\\Main.xml");//输出文件路径
             //生成XMLWriter对象,构造函数中的参数为需要输出的文件流和格式
             
    XMLWriter writer = new XMLWriter(new FileOutputStream(files), format);
    //开始写入,write方法中包含上面创建的Document对象
    writer.write(doc);
    writer.close();
         }  
         else{  
             return false;  
         }  
     } catch (Exception e) {  
     } finally {  
     xmlfile = null;  
     }  

     return false; 

    }

   public static void main(String[] args) throws Exception {
createMainXml();
   }

}

生成xml示例,如下图:



猜你喜欢

转载自blog.csdn.net/li1325169021/article/details/80730544
今日推荐