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

 
發佈了22 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章