1. 程式人生 > >Java動態生成XML檔案

Java動態生成XML檔案

1.說明

在工作中,需要將Java集合中的資料儲存到XML檔案中。

在此總結一下,動態儲存資料到XML檔案的方法。

2.Java原始碼

(1)打入XML相關的Jar包

(2)要生成的JavaBean物件

package com.test;
public class Person {
	private String name;
	private int age;
	public Person(){}
	
	public Person(String name, int age) {
	  super();
	  this.name = name;
	  this.age = age;
	}
	
	public String getName() {
	 	return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) {
		this.age = age;
	}
}

(3)動態生成XML檔案工具類

package com.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XmlGeneratorUtil {
	//對應JavaBean的類名(包名+類名)
	public  static String JAVA_FULL_NAME="";
	//生成的XML的檔名
	private static String XML_FILE_NAME="";
	
	/**
	 * 生成XML檔案
	 * @param list
	 * @param className :包名+類名
	 * @return
	 */
	public static void createXmlDocument(List<Object> list,String javaClassName) {
		try {
			//設定全域性屬性
			JAVA_FULL_NAME=javaClassName;
			int lastIndexOf = javaClassName.lastIndexOf('.');
			if(lastIndexOf!=-1){
				XML_FILE_NAME= javaClassName.substring(lastIndexOf+1);
			}
			//將集合物件轉換為XML檔案內容
			Document doc = generateXMLContents(list);
			//生成XML檔案
			DOMSource source = new DOMSource(doc);
			TransformerFactory tf = TransformerFactory.newInstance();
			//設定縮排量
			tf.setAttribute("indent-number", new Integer(3));
			Transformer transformer = tf.newTransformer();
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			//設定文件的換行與縮排
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			//合成檔案路徑
			String xmlFilePath = System.getProperty("user.dir");
			File file = new File(xmlFilePath +"\\"+ XML_FILE_NAME +".xml");
			
			//寫入檔案
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			PrintWriter pw = new PrintWriter(fileOutputStream);
			StreamResult result = new StreamResult(pw);
			transformer.transform(source, result);
			System.out.println("生成XML檔案成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/***
	 * 將集合物件轉換為XML檔案內容
	 * @param list
	 * @param className
	 * @return
	 */
	public static Document generateXMLContents(List<Object> list) {
		Document doc=null;
		Element root = null;
		try {
			//建立新文件
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			doc = builder.newDocument();
			doc.setXmlStandalone(true); 
			//第一行
			root = doc.createElement("Result");
			root.setAttribute("Total_Size", ""+list.size());
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
			String timeDate = df.format(new Date());
			root.setAttribute("time", timeDate);
			doc.appendChild(root);
			
			//反射機制獲得所有屬性
			Class c = Class.forName(JAVA_FULL_NAME);
			Method[] methods = c.getMethods();
			Field[] fields = c.getDeclaredFields();

			//遍歷集合,一個物件一行
			for (Object obj: list) {
				//節點名稱為JAVA檔案類名
				Element element = doc.createElement(XML_FILE_NAME);
				for(Field field:fields){
					String fieldName = field.getName();
					//根據屬性名合成方法名
					String methodName ="get"+ fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
					//動態獲取該方法
					Method method = c.getMethod(methodName, null);
					//動態呼叫該方法
					Object invoke = method.invoke(obj, null);
					if(invoke==null){
						invoke ="";
					}
					//新增屬性
					element.setAttribute(fieldName,invoke.toString());
				}
				root.appendChild(element);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return doc;
	}
}

(4)執行類

package com.test;

import java.util.Arrays;
import java.util.List;

public class XmlGeneratorDemo {
	public static void main(String[] args) {
		try {
			Object[] arr = new Person[] {
					new Person("lily", 20),
					new Person("lucy", 25),
					new Person("Tom", 15),
					new Person("Jack", 35)
			};
			// 將陣列轉換成List
			List<Object> list = Arrays.asList(arr);
			// 生成XML檔案
			String name = Person.class.getName();
			XmlGeneratorUtil.createXmlDocument(list,name);
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("出現異常");
		}
	}
}

3.結果

重新整理一下專案,專案的根目錄下生成了Person.xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<Result Total_Size="4" time="2014-06-06 10:42:19">
   <Person age="20" name="lily"/>
   <Person age="25" name="lucy"/>
   <Person age="15" name="Tom"/>
   <Person age="35" name="Jack"/>
</Result>