创建xml


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;
	}	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值