Java动态⽣成XML⽂件
1.说明java xml是什么
在⼯作中,需要将Java集合中的数据保存到XML⽂件中。
在此总结⼀下,动态保存数据到XML⽂件的⽅法。
2.Java源码
(1)打⼊XML相关的Jar包
(2)要⽣成的JavaBean对象
st;
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⽂件⼯具类
st;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import flect.Field;
import flect.Method;
DateFormat;
SimpleDateFormat;
import java.util.Date;
import java.util.Date;
import java.util.List;
l.parsers.DocumentBuilder;
l.parsers.DocumentBuilderFactory;
l.transform.OutputKeys;
l.transform.Transformer;
l.transform.TransformerFactory;
l.transform.dom.DOMSource;
l.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 = wInstance();
//设置缩进量
tf.setAttribute("indent-number", new Integer(3));
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
//设置⽂档的换⾏与缩进
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//合成⽂件路径
String xmlFilePath = Property("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);
System.out.println("⽣成XML⽂件成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
/***
* 将集合对象转换为XML⽂件内容
* @param list
* @param className
* @return
*/
public static Document generateXMLContents(List<Object> list) {
public static Document generateXMLContents(List<Object> list) {
Document doc=null;
Element root = null;
try {
//创建新⽂档
DocumentBuilderFactory factory = wInstance();
DocumentBuilder builder = wDocumentBuilder();
doc = wDocument();
doc.setXmlStandalone(true);
//第⼀⾏
root = ateElement("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 = ateElement(XML_FILE_NAME);
for(Field field:fields){
String fieldName = Name();
//根据属性名合成⽅法名
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(String());
}
root.appendChild(element);
}
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
}
(4)执⾏类
st;
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 = Name();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.结果
刷新⼀下项⽬,项⽬的根⽬录下⽣成了l⽂件
<?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>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。