解析XML

package com.example.springboot09.com.test;

import com.example.springboot09.com.pojo.Student;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * @Author: Administrator
 * @Description:
 * @Date: 2019-09-05 11:21
 * @Modified By:
 */
public class Test6 {

    public static void main(String[] args) {
        String xml="\n"
                +"\t\n" +
                "\t410031401\n" +
                "\t高三十四班\n" +
                "\t周瑜\n" +
                "\t16\n" +
                "\t\n" +
                "\t180.81\n" +
                "\t60.23\n"+
                "";
         HashMap result=fromSecondXml(xml, Student.class,"list");
            System.out.println(result.toString());
    }

    /**
     * 解析XML字符串 多笔需要封装List
     * @param xml
     * @param clazz
     * @param elementName 节点名称
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static HashMap fromSecondXml(String xml, Class clazz, String elementName) {

        HashMap stringHashMap = new HashMap();
        SAXReader reader = new SAXReader();
        try {
            org.dom4j.Document doc = reader.read(new ByteArrayInputStream(xml
                    .getBytes("GBK")));
            org.dom4j.Element Result = doc.getRootElement();//根节点
            org.dom4j.Element element;//子节点

            //获取对象属性名称数组
            Field[] fields = clazz.getDeclaredFields();
            String attributeValue = "";

            for (int j = 0; j < fields.length; j++) {
                for (Iterator i = Result.elementIterator(elementName); i.hasNext(); ) {
                    element = (org.dom4j.Element) i.next();
                    //该属性名相对于的节点内容
                    attributeValue = element.elementText(fields[j].getName());
                    //封装到map中
                    stringHashMap.put(fields[j].getName(),element.elementText(fields[j].getName()));
                }
                if(attributeValue == null || "".equalsIgnoreCase(attributeValue)){
                    stringHashMap.put(fields[j].getName(),Result.elementText(fields[j].getName()));
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return stringHashMap;
    }

    /**
     * 批量请求,最终获取结果需封装list集合批量展示
     * @param xml
     * @param clazz
     * @param elementName 节点名称
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static List> fromSecondXmlList(String xml, Class clazz, String elementName) {
        List> resultList=new ArrayList>();
        HashMap stringHashMap = new HashMap();

        SAXReader reader = new SAXReader();
        try {
            org.dom4j.Document doc = reader.read(new ByteArrayInputStream(xml
                    .getBytes("GBK")));
            org.dom4j.Element Result = doc.getRootElement();//根节点
            org.dom4j.Element element;//子节点
            //获取list出现的次数
            int count = 0;
            while(xml.indexOf("") != -1) {
                xml = xml.substring(xml.indexOf("") + 1,xml.length());
                count++;
            }

            //获取对象属性名称数组
            Field[] fields = clazz.getDeclaredFields();
            String attributeValue = "";
            for (int l=0;l<=count-1;l++){
                for (int j = 0; j < fields.length; j++) {
                    for (Iterator i = Result.elementIterator(elementName); i.hasNext(); ) {
                        element = (org.dom4j.Element) i.next();
                        //该属性名相对于的节点内容
                        attributeValue = element.elementText(fields[j].getName());
                        //封装到map中
                        stringHashMap.put(fields[j].getName(),element.elementText(fields[j].getName()));
                    }
                    if (attributeValue == null || "".equalsIgnoreCase(attributeValue)) {
                        stringHashMap.put(fields[j].getName(), Result.elementText(fields[j].getName()));
                    }
                }
                resultList.add(stringHashMap);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return resultList;
    }

}

实体类

package com.example.springboot09.com.pojo;

import javax.xml.bind.annotation.*;

/**
 * @Author: Administrator
 * @Description: 学生类
 * @Date: 2019-09-04 16:58
 * @Modified By:
 */

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Result")
@XmlType(name = "",propOrder = {
        "id",
        "clazz",
        "name",
        "age",
        "sex",
        "height",
        "weight"
})
public class Student {

    @XmlElement(name = "ID",required = true)
    private String id;
    @XmlElement(name = "CLAZZ",required = true)
    private String clazz;
    @XmlElement(name = "NAME",required = true)
    private String name;
    @XmlElement(name = "AGE",required = true)
    private Integer age;
    @XmlElement(name = "SEX",required = true)
    private String sex;
    @XmlElement(name = "HEIGHT",required = true)
    private double height;
    @XmlElement(name = "WEIGHT",required = true)
    private Double weight;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getClazz() {
        return clazz;
    }

    public void setClazz(String clazz) {
        this.clazz = clazz;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public Double getWeight() {
        return weight;
    }

    public void setWeight(Double weight) {
        this.weight = weight;
    }
}

你可能感兴趣的:(java)