將實體類轉化爲XML

1.創建實體對象
2.創建Document對象
3.創建根節點
4.添加子節點
5.給子節點添加值
6.設置文檔輸出格式爲XML,指定編碼
7.利用io流將文件寫出到指定位置

public class EntityToXml{
	public static void main(String [] args){
		Car car=new Car(100,"路虎");
		Document doc=DocumentHelper.creatDocument();//得到Document對象
		Element root=doc.addElement("Cars");//創建根節點
		Element first=root.addElement("car");//創建子節點
		Element first_a=first.addElement("id");//創建子節點的子節點
		first_a.setText(String.valueOf(car.getId()))//設置子節點的子節點中的內容
		Element first_b=first.addElement("name");//添加另外的子節點
		first_b.setText(car.getName());
		OutputFormat of=OutputFormat.createPrettyPrint();//指定文檔輸出格式爲XML
		of.setEncoding("utf-8");//設置編碼
		Write out; 
		try{
				out=new FileWriter("F://car.xml");//創建輸出流對象,將文件寫到F盤
				XMLWriter writer=new XMLWriter(out.of);//創建一個dom4j創建的解析對象
				writer.write(doc);//將文件寫出
				writer.close();//關流
				System.out.println("生成XML文件成功")
			}catch(IOException e){
			System.out.println("生成XML文件失敗");
			e.printStackTrace();
}
}		
		
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章