zoukankan      html  css  js  c++  java
  • 生成XML文件

    import java.io.FileOutputStream;
    import java.io.IOException;

    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.JDOMException;
    import org.jdom.output.Format;
    import org.jdom.output.XMLOutputter;

    public class CreateXML {

        Book[] books = new Book[] { new Book("1", "唐诗三百首"),
                new Book("2", "Think in Java"), new Book("3", "神雕侠侣"),
                new Book("4", "葵花宝典") };

        public void buildXMLDoc() throws IOException, JDOMException {
            // 创建根节点 并设置它的属性 ;
            Element root = new Element("books").setAttribute("count", "4");
            // 将根节点添加到文档中;
            Document doc = new Document(root);

            for (int i = 0; i < books.length; i++) {
                // 创建节点 book;
                Element elements = new Element("book");
                // 给 book 节点添加子节点并赋值;
                elements.addContent(new Element("id").setText(books[i].getId()));
                elements.addContent(new Element("name").setText(books[i].getName()));
                //
                root.addContent(elements);
            }
            // 输出 books.xml 文件;
            // 使xml文件 缩进效果
            Format format = Format.getPrettyFormat();
            XMLOutputter xmlOut = new XMLOutputter(format);
           xmlOut.output(doc, new FileOutputStream("c:/books.xml"));
        }

        public static void main(String[] args) {
            try {
                CreateXML createXML = new CreateXML();
                System.out.println("正在生成 books.xml 文件...");
                createXML.buildXMLDoc();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("c:/books.xml 文件已生成");
        }

        class Book {
            private String id;
            private String name;

            public Book(String id, String name) {
                super();
                this.id = id;
                this.name = name;
            }

            public String getId() {
                return id;
            }

            public void setId(String id) {
                this.id = id;
            }

            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }
        }
    }

  • 相关阅读:
    Java学习第一周汇报
    Java暑期学习第八天日报
    Java暑期学习第十天日报
    Java暑期学习第十二天日报
    Java学习第二周汇报
    Java暑期学习第九天日报
    0006 列表(ul、ol、dl)
    0015 行高那些事:lineheight
    0016 CSS 背景:background
    HTTP中GET与POST的区别 99%的错误认识
  • 原文地址:https://www.cnblogs.com/BrightPoplar/p/4836596.html
Copyright © 2011-2022 走看看