JAVA 读写XML(一) 使用(JDOM)

使用java jdom 写xml文件

public void writeXml(){
        Document doc=new Document();
        Element root=new Element("Actors");
        doc.setRootElement(root);

        Element employee=new Element("Actress");
        employee.addContent(new Element("id").setText("001"));
        employee.addContent(new Element("name").setText("李冰冰"));
        employee.addContent(new Element("sex").setText("女"));
        employee.addContent(new Element("occupation").setText("演员"));
        root.addContent(employee);

        employee=new Element("Actress");
        employee.setAttribute("id", "002");
        employee.addContent(new Element("name").setText("周迅"));
        employee.addContent(new Element("sex").setText("女"));
        employee.addContent(new Element("occupation").setText("演员")).setAttribute("secoccupation", "歌手");
        root.addContent(employee);

        Element male=new Element("Actor");

        Element actor=new Element("actor");
        //actor.addContent("id").setText("003");
        actor.setAttribute("id", "003");
        actor.addContent(new Element("name").setText("张涵予"));
        actor.addContent(new Element("occupation").setText("演员"));
        male.addContent(actor);

        actor=new Element("actor");
        actor.setAttribute("id", "004");
        actor.addContent(new Element("name").setText("黄晓明"));
        actor.addContent(new Element("occupation").setText("演员")).setAttribute("secoccupation", "歌手");
        male.addContent(actor);
        root.addContent(male);

        try {
            XMLOutputter out=new XMLOutputter(Format.getPrettyFormat());
            //out.output(doc, new FileWriter(new File("e:\\wind.xml")));
            out.output(doc, new FileOutputStream(new File("e:\\wind.xml")));
        } catch (Exception e) {
            System.out.println("异常发生了!");
        }
    }

相关推荐