1、先下载 包 http://download.csdn.net/detail/u010310183/8078033
2、在E盘 创建一个 xml 文件 名字是: E:\\LOG_huoxin.xml 格式如下
<?xml version="1.0" encoding="GBK"?>
<Pa_Cx_Datas>
<Pa_Cx_Data>
<I_ID>0</I_ID>
<I_TYPE>1</I_TYPE>
<I_PUBTIME>2014-09-23 09:59:32</I_PUBTIME>
<I_URL>http://www.jl.chinanews.com/news1-110241.html</I_URL>
<I_TITLE>世界第一支“fe”生物牙膏的由来</I_TITLE>
<I_TOPIC>0</I_TOPIC>
<I_TOPIC2>0</I_TOPIC2>
<I_AUTHOR></I_AUTHOR>
<I_AREA>0</I_AREA>
<I_DOMAIN>chinanews.com</I_DOMAIN>
<I_MEDIA>中新网</I_MEDIA>
<I_MEDIATYPE>0</I_MEDIATYPE>
<I_DOMESTIC>0</I_DOMESTIC>
<I_LANGUAGE>0</I_LANGUAGE>
<I_SOURCE></I_SOURCE>
<I_KEYWORDS></I_KEYWORDS>
<I_ABSTRACT></I_ABSTRACT>
<I_PIC></I_PIC>
<I_CONTENT>这里表示文章的正文</I_CONTENT>
<I_VNUM></I_VNUM>
<I_RNUM>0</I_RNUM>
<I_CNUM>0</I_CNUM>
<I_HOT>0</I_HOT>
<I_RECOM>0</I_RECOM>
<I_FEEL>0</I_FEEL>
<I_S_SAD>0</I_S_SAD>
<I_S_ANGER>0</I_S_ANGER>
<I_S_HAPPY>0</I_S_HAPPY>
<I_S_SUP>0</I_S_SUP>
<I_S_FEAR>0</I_S_FEAR>
<I_CONN>0</I_CONN>
<I_WARN>0</I_WARN>
<I_COLLECT>0</I_COLLECT>
<I_ISLEADER>0</I_ISLEADER>
<I_ISMINE>0</I_ISMINE>
<I_ISAREA></I_ISAREA>
<I_ISRIVAL>0</I_ISRIVAL>
<I_VIEWS>0</I_VIEWS>
<I_INPUTTIME>2014-10-13 09:59:36</I_INPUTTIME>
<I_FIRSTID>0</I_FIRSTID>
<I_COMEFROM>6</I_COMEFROM>
<WorkStatu>0</WorkStatu>
<OLDID></OLDID>
<C_ID>sda_1</C_ID>
<I_SHOW></I_SHOW>
<I_REPEATNUM></I_REPEATNUM>
<I_REPEATGROUP></I_REPEATGROUP>
<I_DAYS></I_DAYS>
<I_HOURS></I_HOURS>
</Pa_Cx_Data>
</Pa_Cx_Datas>
3、创建类 内容如下
import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.dom4j.Document;
import org.dom4j.DocumentException;
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.yq.pa_cx_data.utils.Pa_Cx_Data;
/**
* 利用Dom4J读取XML
* @author 赵九龙
*
*/
public class Dom4jXml {
/**
* 解析xml文件
* @param filename
* @return
* @throws SecurityException
* @throws IllegalArgumentException
* @throws NoSuchMethodException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public Queue<Pa_Cx_Data> iterateWholeXML(String filename) throws SecurityException, IllegalArgumentException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException{
Queue<Pa_Cx_Data> WorkQueue = new ConcurrentLinkedQueue<Pa_Cx_Data>();
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(new File(filename));
Element root = document.getRootElement();
//遍历根结点的所有孩子节点
for ( Iterator<?> iter = root.elementIterator(); iter.hasNext(); ) {
Pa_Cx_Data data =new Pa_Cx_Data();
Element element = (Element) iter.next();
//遍历结点的所有孩子节点,并进行处理
Map<String, String> map = new HashMap<String, String>();
for ( Iterator<?> iterInner = element.elementIterator(); iterInner.hasNext(); ) {
Element elementInner = (Element) iterInner.next();
map.put(elementInner.getName(), elementInner.getText());
}
if(map!=null && map.size()>0){
data = (Pa_Cx_Data)nodeToBean(map,Pa_Cx_Data.class);
}
WorkQueue.add(data);
}
}catch (DocumentException e) {
e.printStackTrace();
}
return WorkQueue;
}
public List<Pa_Cx_Data> iterateXML(String filename) throws SecurityException, IllegalArgumentException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException{
List<Pa_Cx_Data> WorkQueue = new ArrayList<Pa_Cx_Data>();
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(new File(filename));
Element root = document.getRootElement();
//遍历根结点的所有孩子节点
for ( Iterator<?> iter = root.elementIterator(); iter.hasNext(); ) {
Pa_Cx_Data data =new Pa_Cx_Data();
Element element = (Element) iter.next();
//遍历结点的所有孩子节点,并进行处理
Map<String, String> map = new HashMap<String, String>();
for ( Iterator<?> iterInner = element.elementIterator(); iterInner.hasNext(); ) {
Element elementInner = (Element) iterInner.next();//获取节点名字:elementInner.getName() , 获取节点内容: elementInner.getText()
//System.out.println(elementInner.getText());
map.put(elementInner.getName(), elementInner.getText());//存入map
}
if(map!=null && map.size()>0){
data = (Pa_Cx_Data)nodeToBean(map,Pa_Cx_Data.class);//data是 xml文件中 全部内容
//System.out.println(data);
}
WorkQueue.add(data);
}
}catch (DocumentException e) {
e.printStackTrace();
}
return WorkQueue;
}
/**
* 用java的反射机制,根据xml数据,实例化对象,并返回
* @param map 保存xml信息的map
* @param classType 要生成的对象的类型
* @return 实例化对象,填充数据,并返回该对象
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private static Object nodeToBean(final Map<String, String> map, final Class<?> classType) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException
{
Field[] fields = classType.getDeclaredFields();//获取类中的所有字段
Object obj = classType.getConstructor().newInstance();//返回该类中的 所有属性
// System.out.println(obj);
for(Field field : fields)
{
//属性名
String fieldName = field.getName(); //所有名字
if(!map.containsKey(fieldName))//判断是否有 对应的value
{
continue;
}
Object param = field.getType().getConstructor(String.class).newInstance(map.get(fieldName));
//System.out.println(param);
//根据方法的命名规范,获取该属性的set方法
String methodName = "set" + fieldName; //自己拼写 类中的 set方法
Method method = classType.getMethod(methodName, field.getType());//
// System.out.println(method);
method.invoke(obj, param);//将类 属性赋值给obj
}
return obj;
}
/**
* 创建xml
* @param obj 对象
* @param entityPropertys 对象的List集合
* @param Encode XML自定义编码类型
* @param XMLPath XML文件的路径及文件名
*/
public static boolean createXmlDocument(Pa_Cx_Data obj, List<Pa_Cx_Data> entityPropertys, String Encode, String XMLPath ,String unique) {
long now = System.currentTimeMillis();
// File pathFile = new File(XMLPath);
// if(!pathFile.exists()){
// pathFile.mkdirs();
// }
File file = new File(XMLPath+now +unique+".xml");// (生成文件的名称)
//System.out.println(file);
try {
XMLWriter writer = null;// 声明写XML的对象
OutputFormat format = OutputFormat.createPrettyPrint(); //格式化输出
format.setEncoding(Encode); // 设置XML文件的编码格式 UTF-8
format.setIndentSize(2);
format.setNewlines(true);
format.setTrimText(false);
format.setPadText(true);
if (file.exists()) { //判断你指定的路径或着指定的目录文件是否已经存在。
file.delete();
}
// 创建xml文件
Document document = DocumentHelper.createDocument(); // 创建一个document
String rootname = obj.getClass().getSimpleName(); //获得简单类名
Element root = document.addElement(rootname + "s");//添加根节点
Field[] properties = obj.getClass().getDeclaredFields();//获得实体类的所有属性
//赋值
for (Pa_Cx_Data t : entityPropertys) { //递归实体
Element element = root.addElement(rootname); //二级节点
for (int i = 0; i < properties.length; i++) {
//反射get方法
Method meth = t.getClass().getMethod("get"+ properties[i].getName()); //所有属性 get方法
//为二级节点添加属性,属性值为对应属性的值
String value = meth.invoke(t)==null ? "":meth.invoke(t).toString();//拿到所有属性值
element.addElement(properties[i].getName()).setText(value);
//System.out.println(element.getName());
}
}
writer = new XMLWriter(new FileOutputStream(file), format);
writer.write(document);
writer.close(); //写入完毕
} catch (Exception e) {
System.out.println("XML文件写入失败");
e.printStackTrace();
}
if(file.exists()){
return true;
}else{
return false;
}
}
public static boolean createXmlDocument(Pa_Cx_Data obj, Queue<Pa_Cx_Data> entityPropertys, String Encode, String XMLPath ,String unique) {
long now = System.currentTimeMillis();
// File pathFile = new File(XMLPath);
// if(!pathFile.exists()){
// pathFile.mkdirs();
// }
File file = new File(XMLPath+now +unique+".xml");//获得文件
try {
XMLWriter writer = null;// 声明写XML的对象
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(Encode); // 设置XML文件的编码格式 UTF-8
format.setIndentSize(2);
format.setNewlines(true);
format.setTrimText(false);
format.setPadText(true);
if (file.exists()) {
file.delete();
}
// 创建xml文件
Document document = DocumentHelper.createDocument();
String rootname = obj.getClass().getSimpleName(); //获得简单类名
Element root = document.addElement(rootname + "s");//添加根节点
Field[] properties = obj.getClass().getDeclaredFields();//获得实体类的所有属性
//赋值
for (Pa_Cx_Data t : entityPropertys) { //递归实体
Element element = root.addElement(rootname); //二级节点
for (int i = 0; i < properties.length; i++) {
//反射get方法
Method meth = t.getClass().getMethod("get"+ properties[i].getName());
//为二级节点添加属性,属性值为对应属性的值
String value = meth.invoke(t)==null ? "":meth.invoke(t).toString();
element.addElement(properties[i].getName()).setText(value);
}
}
writer = new XMLWriter(new FileOutputStream(file), format);
writer.write(document);
writer.close();
} catch (Exception e) {
System.out.println("XML文件写入失败");
e.printStackTrace();
}
if(file.exists()){
return true;
}else{
return false;
}
}
/**
* @param args
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws SecurityException
* @throws SQLException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws SecurityException, IllegalArgumentException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException, SQLException {
Dom4jXml dom4jXml = new Dom4jXml();
// List<Pa_Cx_Data> WorkList = dom4jXml.iterateXML("E:\\20131105141704docinfo.xml");
// createXmlDocument(new Pa_Cx_Data(),WorkList,"GBK","D:\\");
// while(WorkQueue.size()>0){
// Pa_Cx_Data data = WorkQueue.poll();
// System.out.println(data.getI_AUTHOR());
// System.out.println(data.getI_CONTENT());
// System.out.println("****************************************");
// }
List<Pa_Cx_Data> WorkList1 = dom4jXml.iterateXML("E:\\LOG_huoxin.xml"); //返回一个list 里面是 要生成的xml内容 (也就是E:\\LOG_huoxin.xml 这个xml的内容)
long start = System.currentTimeMillis();//时间显示
createXmlDocument(new Pa_Cx_Data(),WorkList1,"GBK","D:\\","");//创建xml完毕
long end = System.currentTimeMillis();
System.out.println(end -start);
// while(WorkQueue.size()>0){
// Pa_Cx_Data data = WorkQueue.poll();
// System.out.println(data.getI_AUTHOR());
// System.out.println(data.getI_CONTENT());
// System.out.println("****************************************");
// }
}
}
我的注视都卸载了 代码上 。 希望对大家有帮助
详情方法了解 看这里:http://blog.csdn.net/hbcui1984/article/details/1270163