Custom class library: Java conversion xml file conversion pojo tool

1. When java read the xml configuration file, it was always actively parsed through the dom4j third-party library. Recently, it was found that the xml can be converted to pojo through the jdk class library.

Second, write the xml conversion tool class XmlUtils

package com.moy.demo.common.utils;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;

/**
 * [Project]:cloud-demo-master  <br/>
 * [Email]:[email protected]  <br/>
 * [Date]:2018/4/30  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */ 
public  abstract  class XmlUtils {

    public static <T> T xmlFileToObject(String xmlFilePath, Class<T> clazz) {
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        try (InputStream inputStream = contextClassLoader.getResourceAsStream(xmlFilePath)) {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            T result = (T) unmarshaller.unmarshal(inputStream);
            return result;
        } catch (Exception e) {
            throw new RuntimeException("convert xml to POJO failure!", e);
        }
    }

    public static <T> T xmlStringToObject(String xmlString, Class<T> clazz) {
        try (Reader reader = new StringReader(xmlString)) {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            T result = (T) unmarshaller.unmarshal(reader);
            return result;
        } catch (Exception e) {
            throw new RuntimeException("convert xml string to POJO failure!", e);
        }
    }
}

2. Test

  a. The first step: define an xml configuration file such as: cityList.xml

<?xml version="1.0" encoding="UTF-8" ?>
<c c1="0">
    <d d1="101020100" d2="上海" d3="shanghai" d4="上海"/>
    <d d1="101220101" d2="合肥" d3="hefei" d4="安徽"/>
    <d d1="101190101" d2="南京" d3="jiangshu" d4="江苏"/>
    <d d1="101010100" d2="北京" d3="beijing" d4="北京"/>
    <d d1="101270101" d2="成都" d3="chengdu" d4="四川"/>
</c>
View Code

  b. Step 2: Write the entity City and CityList corresponding to xml, and add corresponding annotations

package com.moy.demo.common.utils;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * [Project]:cloud-demo-master  <br/>
 * [Email]:[email protected]  <br/>
 * [Date]:2018/4/30  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
@XmlRootElement(name = "d")
@XmlAccessorType(XmlAccessType.FIELD)
public class City {
    @XmlAttribute(name = "d1")
    private String cityId;
    @XmlAttribute(name = "d2")
    private String cityName;
    @XmlAttribute(name = "d3")
    private String cityCode;
    @XmlAttribute(name = "d4")
    private String province;

    public String getCityId() {
        return cityId;
    }

    public void setCityId(String cityId) {
        this.cityId = cityId;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public String getCityCode() {
        return cityCode;
    }

    public void setCityCode(String cityCode) {
        this.cityCode = cityCode;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    @Override
    public String toString() {
        return "City{" +
                "cityId='" + cityId + '\'' +
                ", cityName='" + cityName + '\'' +
                ", cityCode='" + cityCode + '\'' +
                ", province='" + province + '\'' +
                '}';
    }
}
View Code
package com.moy.demo.common.utils;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;

/**
 * [Project]:cloud-demo-master  <br/>
 * [Email]:[email protected]  <br/>
 * [Date]:2018/4/30  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
@XmlRootElement(name = "c")
@XmlAccessorType(XmlAccessType.FIELD)
public class CityList {
    @XmlElement(name = "d")
    private List<City> cityList;

    public List<City> getCityList() {
        return cityList;
    }

    public void setCityList(List<City> cityList) {
        this.cityList = cityList;
    }

    @Override
    public String toString() {
        return "CityList{" +
                "cityList=" + cityList +
                '}';
    }
}
View Code

  c, write unit test XmlUtilsTest

package com.moy.demo.common.utils;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * [Project]:demo-master  <br/>
 * [Email]:[email protected]  <br/>
 * [Date]:2018/5/2  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */ 
public  class XmlUtilsTest {

    @Test
    public void xmlFileToObject() {
        CityList cityList = XmlUtils.xmlFileToObject("cityList.xml", CityList.class);
        System.out.println(cityList);
    }

    @Test
    public void xmlStringToObject() {
        String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
                "<c c1=\"0\">\n" +
                "    <d d1=\"101020100\" d2=\"上海\" d3=\"shanghai\" d4=\"上海\"/>\n" +
                "    <d d1=\"101220101\" d2=\"合肥\" d3=\"hefei\" d4=\"安徽\"/>\n" +
                "    <d d1=\"101190101\" d2=\"南京\" d3=\"jiangshu\" d4=\"江苏\"/>\n" +
                "    <d d1=\"101010100\" d2=\"北京\" d3=\"beijing\" d4=\"北京\"/>\n" +
                "    <d d1=\"101270101\" d2=\"成都\" d3=\"chengdu\" d4=\"四川\"/>\n" +
                "</c>";

        CityList cityList = XmlUtils.xmlStringToObject(xmlString, CityList.class);
        System.out.println(cityList);
    }

}
View Code

  

 

yexiangyang

[email protected]


 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325166197&siteId=291194637