Java_ABC_5.写入XML

package xml;

import java.io.FileOutputStream;

import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 * 生成XML文档
 * 
 * @author Administrator
 * 
 */
public class XmlGenerator {
	
	Element root = null;
	Document document = null;
	String xmlFileName = null;
	boolean m_bIsWrite = true;
	
	/**
	 * 生成XML文件的root结点
	 * 
	 * @param xmlName
	 */
	public XmlGenerator(String xmlFileName) 
	{
		document = DocumentFactory.getInstance().createDocument();//构造Document对象
		root = document.addElement("users");//添加根节点,名称为user
		document.setRootElement(root);//设置root为根节点
		this.xmlFileName = xmlFileName;
		m_bIsWrite = true;
	}
	
	public XmlGenerator() 
	{
		document = DocumentFactory.getInstance().createDocument();//构造Document对象
		root = document.addElement("users");//添加根节点,名称为user
		document.setRootElement(root);//设置root为根节点
		m_bIsWrite = false;
	}

	/**
	 * 生成XML文件
	 * @param
	 * 
	 */
	public void createDocument(int _id, String _nickname, String _email, String _fullname,String _sms)
	{
		//为root根节点增加下一级节点node,名称为user
		Element node_user = root.addElement("user");
		
		//为node增加下一级节点,名称分别为。。。
		Element node_id = node_user.addElement("id");
		Element node_nickname = node_user.addElement("nickname");
		Element node_email = node_user.addElement("email");
		Element node_fullname = node_user.addElement("fullname");
		Element node_sms = node_user.addElement("sms");
		
		//为子节点增加内容
		node_id.addText(_id+"");
		node_nickname.addText(_nickname);
		node_email.addText(_email);
		node_fullname.addText(_fullname);
		node_sms.addText(_sms);
		
		if(m_bIsWrite)
		{
			writeDocument();
		}
	}
	
	private void writeDocument()
	{
		try
		{
			XMLWriter writer = new XMLWriter(new FileOutputStream(xmlFileName), OutputFormat.createPrettyPrint());
			writer.write(document);
			writer.flush();
			writer.close();
		} 
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值