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; } }原文链接:https://www.f2er.com/xml/294690.html