欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

xml文件和java对象之间转换 博客分类: Java EE xmljava 

程序员文章站 2024-03-23 19:34:22
...
xml文件和java对象之间转换 例:
package com.zgs.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import com.zgs.entity.Order;
/**
*
* @author Administrator
* 2015-4-6
*
*/
public class XMLUtil{

/**
* 解析XML文件为对象集合
* InputStream Is为Xml文件流
* @return
*/
public static List XMLToList(InputStream Is)throws Exception{
SAXReader saxReader=new SAXReader();
Document doc=saxReader.read(Is);
//获取根元素
Element root=doc.getRootElement();
//获取集合元素
List<Element> orders=root.elements("order");
List<Order> list=new ArrayList<Order>();
//遍历出集合元素的值
for(Element e:orders){
Order o=new Order();
o.setName(e.elementText("name"));
o.setDest(e.elementText("dest"));
o.setFlight(e.elementText("flight"));
o.setTime(e.elementText("time"));
o.setType(e.attributeValue("type"));
list.add(o);
}
return list;
}

public static void listToXML(OutputStream os,List<Order> orders)throws Exception{
//创建doc对象
Document doc=DocumentHelper.createDocument();
//创建根元素
Element root=doc.addElement("orders");
//创建order元素
for(Order o:orders){
Element order=root.addElement("order");
order.addElement("name").setText(o.getName());
order.addElement("dest").setText(o.getDest());
order.addElement("flight").setText(o.getFlight());
order.addElement("time").setText(o.getTime());
order.addAttribute("type", o.getType());

}
//定义输出格式
OutputFormat of=OutputFormat.createPrettyPrint();
//输出list为xml
XMLWriter out=new XMLWriter(os, of);
out.write(doc);
out.close();
os.close();
}


public static void main(String[] args) throws Exception{
// List orders=new ArrayList<Order>();
// Order o1=new Order("zgs", "china", "a322", "2015-01-01", "sw");
// Order o2=new Order("zgs1", "china1", "a3221", "2015-01-01", "sw1");
// orders.add(o1);
// orders.add(o2);
File file=new File("C:\\Users\\Administrator\\Workspaces\\config\\order.xml");
// FileOutputStream fos=new FileOutputStream(file);
// listToXML(fos, orders);
FileInputStream fis=new FileInputStream(file);
List<Order> list=XMLToList(fis);
for(int i=0;i<list.size();i++){
System.out.println(list.get(i).getName());
System.out.println(list.get(i).getDest());
System.out.println(list.get(i).getFlight());
System.out.println(list.get(i).getTime());
System.out.println(list.get(i).getType());
}
}
相关标签: xml java