创建xml

来源:互联网 发布:underscore min.js 编辑:程序博客网 时间:2024/06/11 07:13


package com.wxh.xml.create;import java.io.File;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.OutputFormat;import org.dom4j.io.XMLWriter;import com.xml.model.Book;public class CreateDemo {public static void main(String[] args) throws IOException {List<Book> books=new ArrayList<Book>(); books.add(new Book("001", "西游记", "吴承恩", "北京大学出版社", 39.8));books.add(new Book("002", "红楼梦", "曹雪芹", "北京大学出版社", 58.8));books.add(new Book("003", "三国演义", "罗贯中", "北京大学出版社", 34.8));books.add(new Book("004", "水浒传", "施耐庵", "北京大学出版社", 28.8));File file=new File("book.xml");//获取目标文件的输出流FileOutputStream fos=new FileOutputStream(file);//创建文档对象Document document=DocumentHelper.createDocument();//向文档中添加根标签Element root=document.addElement("books");//编辑数据集合,根据数据在文档中生成对应元素和属性for (Book book : books) {Element b=root.addElement("book").addAttribute("bno", book.getBno());b.addElement("name").addText(book.getName());b.addElement("author").addText(book.getAuthor());b.addElement("publish").addText(book.getPublish());b.addElement("price").addText(book.getPrice()+"");}OutputFormat fmt=OutputFormat.createPrettyPrint();XMLWriter writer=new XMLWriter(fos,fmt);writer.write(document);writer.flush();writer.close();}}


Book.Java

package com.xml.model;public class Book {private String bno; //编号private String name; //书名private String author;//作者private String publish;//出版社private double price;//单价public Book() {}public Book(String bno, String name, String author, String publish,double price) {super();this.bno = bno;this.name = name;this.author = author;this.publish = publish;this.price = price;}public String getBno() {return bno;}public void setBno(String bno) {this.bno = bno;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public String getPublish() {return publish;}public void setPublish(String publish) {this.publish = publish;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}}


0 0