java解析xml文件,DOM4J解析

xml文件如下:



    
        1
        5
        155
        55
    
    
        2
        5
        176
        55
    
    
        3
        5
        199
        55
    
    
        4
        5
        223
        55
    
    
        5
        0
        95
        308
    
    
        6
        0
        95
        333
    


一,首先在pom文件中引入dom4j的jar包依赖


        
            dom4j
            dom4j
            1.6.1
        

二,xml文件中的对象类如下:

package testForFun.demo20190115.demo_dofj;

/**
 * Created with IntelliJ IDEA
 * User:Ryan
 * Date:2019/1/15
 * Time:14:29
 */
public class Point {

    private Integer ID;
    private Double X;
    private Double Y;
    private Integer Type;

    @Override
    public String toString() {
        return "Point{" +
                "ID=" + ID +
                ", X=" + X +
                ", Y=" + Y +
                ", Type=" + Type +
                '}';
    }

    public Integer getID() {
        return ID;
    }

    public void setID(Integer ID) {
        this.ID = ID;
    }

    public Double getX() {
        return X;
    }

    public void setX(Double x) {
        X = x;
    }

    public Double getY() {
        return Y;
    }

    public void setY(Double y) {
        Y = y;
    }

    public Integer getType() {
        return Type;
    }

    public void setType(Integer type) {
        Type = type;
    }
}

三,简版的解析代码如下:

package testForFun.demo20190115.demo_dofj;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Logger;

/**
 * Created with IntelliJ IDEA
 * User:Ryan
 * Date:2019/1/15
 * Time:14:30
 */
public class PointXml {

    private static Logger logger=Logger.getLogger(PointXml.class.getName());

    private static ConcurrentLinkedQueue pointList=new ConcurrentLinkedQueue();

    private static Point point=new Point();


    public static void main(String[] args) throws DocumentException {


        SAXReader saxReader = new SAXReader();
        InputStream is = PointXml.class.getClassLoader().getResourceAsStream("point.xml");
       //1, 读入xml文件
        Document doc = saxReader.read(is);
        Element rootElement = doc.getRootElement();
        logger.info("根root的名称:"+rootElement.getName());
        //2,得到根节点类型
        Iterator iterator = rootElement.elementIterator("Point");
        //3,遍历所有的子节点
        while (iterator.hasNext()){
            //4,得到第一个子节点
            Element element = (Element)iterator.next();

            String id = element.elementTextTrim("ID");
            String type = element.elementTextTrim("Type");
            String x = element.elementTextTrim("X");
            String y = element.elementTextTrim("Y");

            point.setID(Integer.parseInt(id));
            point.setType(Integer.parseInt(type));
            point.setX(Double.parseDouble(x));
            point.setY(Double.parseDouble(y));

            pointList.add(point);


        }

        logger.info("得到解析后的Point对象集合的大小:"+pointList.size());

        //5,遍历集合显示
        for (Point point :
                pointList) {
            logger.info(point.toString());
        }
    }
}

四,升级版的xml文件解析:

package testForFun.demo20190115.demo_dofj;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import testForFun.demo20190115.demo01.XmlUtil;

import java.io.InputStream;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Logger;

/**
 * Created with IntelliJ IDEA
 * User:Ryan
 * Date:2019/1/15
 * Time:14:53
 */
public class PointXmlPro {

    private static Logger logger=Logger.getLogger(PointXmlPro.class.getName());

    private static ConcurrentLinkedQueue pointList=new ConcurrentLinkedQueue();

    private static Point point=new Point();


    public static void main(String[] args) throws Exception {


        SAXReader saxReader = new SAXReader();
        InputStream is = PointXml.class.getClassLoader().getResourceAsStream("point.xml");
        //1, 读入xml文件
        Document doc = saxReader.read(is);
        Element rootElement = doc.getRootElement();
        logger.info("根root的名称:"+rootElement.getName());
        //2,得到根节点类型
        Iterator iterator = rootElement.elementIterator("Point");
        //3,遍历所有的子节点
        while (iterator.hasNext()){
            //4,得到第一个子节点
            Element element = (Element)iterator.next();

             point = (Point)XmlUtil.fromXmlToBean(element, Point.class);
             pointList.add(point);


        }

        logger.info("得到解析后的Point对象集合的大小:"+pointList.size());

        //5,遍历集合显示
        for (Point point :
                pointList) {
            logger.info(point.toString());
        }

    }
}

XmlUtil工具:

package testForFun.demo20190115.demo01;

/**
 * Created by Ryan on 2017/11/3.
 */


import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class XmlUtil
{
    /**
     * json 数据转换对象
     *
     *            要转换的Element数据
     * @param pojo
     *            要转换的目标对象类型
     * @return 转换的目标对象
     * @throws Exception
     *             转换失败
     */
    @SuppressWarnings("rawtypes")
    public static Object fromXmlToBean(Element rootElt, Class pojo) throws Exception
    {
        // 首先得到pojo所定义的字段
        Field[] fields = pojo.getDeclaredFields();
        // 根据传入的Class动态生成pojo对象
        Object obj = pojo.newInstance();
        for (Field field : fields)
        {
            // 设置字段可访问(必须,否则报错)
            field.setAccessible(true);
            // 得到字段的属性名
            String name = field.getName();
            // 这一段的作用是如果字段在Element中不存在会抛出异常,如果出异常,则跳过。
            try
            {
                rootElt.elementTextTrim(name);
            }
            catch (Exception ex)
            {
                continue;
            }
            if (rootElt.elementTextTrim(name) != null && !"".equals(rootElt.elementTextTrim(name)))
            {
                // 根据字段的类型将值转化为相应的类型,并设置到生成的对象中。
                if (field.getType().equals(Long.class) || field.getType().equals(long.class))
                {
                    field.set(obj, Long.parseLong(rootElt.elementTextTrim(name)));
                }
                else if (field.getType().equals(String.class))
                {
                    field.set(obj, rootElt.elementTextTrim(name));
                }
                else if (field.getType().equals(Double.class) || field.getType().equals(double.class))
                {
                    field.set(obj, Double.parseDouble(rootElt.elementTextTrim(name)));
                }
                else if (field.getType().equals(Integer.class) || field.getType().equals(int.class))
                {
                    field.set(obj, Integer.parseInt(rootElt.elementTextTrim(name)));
                }
                else if (field.getType().equals(Date.class))
                {
                    field.set(obj, Date.parse(rootElt.elementTextTrim(name)));
                }
                else
                {
                    continue;
                }
            }
        }
        return obj;
    }




}

你可能感兴趣的:(java解析xml文件,DOM4J解析)