• 使用DOM4J生成XML文档


    package xml;
    
    import java.io.FileOutputStream;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.dom4j.Document;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;
    import org.dom4j.io.OutputFormat;
    import org.dom4j.io.XMLWriter;
    
    /**
     * @author xingsir
     * 使用DOM4J生成XML文档
     */
    public class WriteXmlDemo {
    
        public static void main(String[] args) {
            List<Dept> deptlist=new ArrayList<>();
            deptlist.add(new Dept(1,"综合部","2020-01-01",400,"孙悟空"));
            deptlist.add(new Dept(2,"人事部","2020-01-01",400,"朱悟能"));
            deptlist.add(new Dept(3,"研发部","2020-01-01",400,"白龙马"));
            deptlist.add(new Dept(4,"销售部","2020-01-01",400,"沙悟净"));
            deptlist.add(new Dept(5,"售后部,","2020-01-01",400,"孙悟空"));
    
    
            try {
                Document doc=DocumentHelper.createDocument();
    
                Element root= doc.addElement("list");
    
                for(Dept d : deptlist) {
                    //向根元素中追加一个<dept>标签
                    Element empEle = root.addElement("dept");
                    //追加部门名称
                    //1 向<dept>标签中追加<name>子标签
                    Element nameEle = empEle.addElement("name");
                    //2 向<name>子标签中追加文本信息
                    nameEle.addText(d.getName());
                    //追加创建时间
                    Element creattime= empEle.addElement("creattime");
                    creattime.addText(d.getCreatetime());
                    //追加年龄
                    Element ageEle = empEle.addElement("age");
                    ageEle.addText(d.getAge()+"");
                    //追加部长
                    empEle.addElement("minister").addText(d.getMinister());
                    //追加一个属性:id="xx"
                    empEle.addAttribute("id", d.getId()+"");
                }
                /*
                 * 将Document对象通过XMLWriter写出以形成 XML文档。
                 */
                XMLWriter writer = new XMLWriter(
                        new FileOutputStream("mydept.xml"),
                        OutputFormat.createPrettyPrint()
                    );
                /*
                 * 将Document对象通过XMLWriter写出以形成XML文档。
                 */
                writer.write(doc);
                
                System.out.println("写出完毕!");
                writer.close();
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    }
  • 相关阅读:
    SpringAOP里JoinPoint常用方法总结
    Hutool工具
    github配置.gitignore忽略版本文件
    IDEA集成Docker部署微服务
    mybatisplus插入报错argument type mismatch
    mysql 主从复制遇到的坑
    博客园文档树参考涉案值
    MySQL分库分表和优化
    mycat中文乱码-解决方案
    ElasticSearch&Docker&Kafka
  • 原文地址:https://www.cnblogs.com/xingsir/p/12161703.html
Copyright © 2020-2023  润新知