• 写XML


    package xml;
    
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.dom4j.Document;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;
    import org.dom4j.io.XMLWriter;
    
    public class WriteXML {
        public static void main(String[] args) {
            List<Student> list = new ArrayList<Student>();
            list.add(new Student("小明", 20, "农", 76));
            list.add(new Student("小周", 18, "一中", 560));
            list.add(new Student("明", 17, "中学", 444));
            
            Document doc = DocumentHelper.createDocument();
            
            Element root = doc.addElement("list");
            
            for(Student stu : list){
                Element subEle = root.addElement("student");
                subEle.addElement("name").addText(stu.getName());
                subEle.addElement("age").addText(stu.getAge()+"");
                subEle.addElement("school").addText(stu.getSchool());
                subEle.addElement("score").addText(stu.getScore()+"");
            }
            try {
                XMLWriter writer = new XMLWriter(new FileOutputStream("stu.xml"));
                writer.write(doc);
                writer.close();
                System.out.println("写出完毕");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            
        }
    }

    运行结果:

    主要的代码:

    Document doc = DocumentHelper.createDocument();
    
    Element root = doc.addRootElement("list");
    
    for(Student stu : list){
    Element ele = root.addElement("student");
    ele.addElement("name").addText(stu.getName());
    ele.addElement("age").addText(stu.getAge());
    ele.addElement("school").addText(stu.getScholl());
    ele.addElement("score").addText(stu.getScore());
    }
    XMLWriter writer = new XMLWriter(new FileOutputStream("stu.xml"));
    writer.write(doc);
    writer.close();
  • 相关阅读:
    [C++]猜词游戏简版
    [C++]异常处理实例-基础版
    C++Primer Plus习题记录-Chapter12
    C++Primer Plus习题记录-Chapter11
    [C++]MI(多继承)实例-基础版
    Windows下编译libevent及使用
    jquery点击回到顶部
    简体繁体转换
    检测ip和地区
    点击复制到剪切板
  • 原文地址:https://www.cnblogs.com/liaoxiaolao/p/9711805.html
Copyright © 2020-2023  润新知