日期:2014-05-16  浏览次数:20448 次

将xml文件导入到oracle数据库
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.lbs.commons.ClassHelper;
import com.lbs.commons.TransManager;
import com.lbs.commons.op.OPException;
import com.lbs.commons.op.OPManager;
import com.start.lemis.apps.commons.code.People;
import com.start.lemis.apps.commons.code.PeopleDTO;
/**
* 将xml文件导入到oracle数据库
* <p>
* Description:
* </p>
* <p>
* Copyright:Copyright(c)2008
* </p>
* Company:实达科技
*
* @author lvrl
* @version 1.0
*/
public class XmlPaser {


/**
* @param fileName
* @param formatStyle
* @param resultType
* @return
*/

public  List  uploadXml(String fileName,String formatStyle,Class resultType){
List allData=new ArrayList();
try {
//dom4j解析器
SAXReader saxReader=new SAXReader();
//读取文件文档
Document document=saxReader.read(new File(fileName));
//根据xml各类标示 获取所有类集合
List list=document.selectNodes(formatStyle);
if(list!=null);
{   for(Iterator it=list.iterator();it.hasNext();)
{
   Element  element=(Element)it.next();
   List elementList=element.elements();
   //返回实体类型
   Object returnInstance = resultType.newInstance();
       for(int i=0;i<elementList.size();i++)
        {
      Element  data=(Element)elementList.get(i);
      BeanUtils.setProperty(returnInstance, data.getName().toLowerCase(), data.getData()); 
        }
      allData.add(returnInstance);
}
}
} catch (Exception e) {
// TODO: handle exception
}
return allData;
}

public static void main(String[] arg)
{
 
        TransManager tm = new TransManager();
        //标记是否启动事务
        int flag = 0;
List allData=null;
    List allPeople=new ArrayList();
XmlPaser temp=new XmlPaser();
allData=temp.uploadXml("C://people.xml", "/PEOPLE/PERSON",PeopleDTO.class);
if(allData!=null){
for(Iterator it=allData.iterator();it.hasNext();)
{
People people=new People();
PeopleDTO dto=(PeopleDTO)it.next();
ClassHelper.copyProperties(dto, people);
allPeople.add(people);
}
}
OPManager op=new OPManager();
try {
flag=tm.begin();
op.saveObjs(allPeople.toArray());
//操作成功,提交
            if(1==flag)
            {
                tm.commit();
                System.out.println("成功导入数据");
            }
} catch (OPException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
}