自定义类库:Java转换xml文件转化pojo工具

Posted moy25

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义类库:Java转换xml文件转化pojo工具相关的知识,希望对你有一定的参考价值。

一、之前java读取xml配置文件时,总是通过dom4j第三方库主动解析,最近发现可以通过jdk类库将xml转换pojo。

二、编写xml转化工具类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);
        }
    }
}

二、测试

  a、第一步:定义一个xml配置文件如: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、第二步:编写xml对应的实体City和CityList,并添加相应注解

技术分享图片
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、编写单元测试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]


 

以上是关于自定义类库:Java转换xml文件转化pojo工具的主要内容,如果未能解决你的问题,请参考以下文章

需要基于 xml-mapping 将 POJO 转换为 XML 和 JSON 的工具

Java - 将xml转换为JAVA Pojo类,包括java注释(Simplexml)

OpenCSV:如何使用自定义列标题和自定义列位置从 POJO 创建 CSV 文件?

关于Mybatis中使用自定义类型通过 自定义TypeHandler类型处理器进行类型转换的两种配置方案-枚举类型示例

怎么将json文件转成xml文件

是否有将 Java POJO 转换为 JSON 和 XML 的库? [关闭]