xml示例(xml格式的txt文件也行):
<?xml version="1.0" encoding="UTF-8"?>
<shopex>
<result>
<![CDATA[success]]>
</result>
<msg>
<![CDATA[]]>
</msg>
<info>
<data_info>
<goods_id>2553</goods_id>
<last_modify>1600714223</last_modify>
<cat_id>240</cat_id>
<category_name>
<![CDATA[化妆工具]]>
</category_name>
<brand_id>218</brand_id>
<brand_name>
<![CDATA[Holika Holika]]>
</brand_name>
<price>40.00</price>
<bn>12000408</bn>
<name>
<![CDATA[韩国 Holika Holika 小猪鼻贴 3片 4件]]>
</name>
<marketable>1</marketable>
<weight>0.000</weight>
<store>8165</store>
<score>-1</score>
<uptime>1489958335</uptime>
<image_default>
<![CDATA[http://www.jtgloble.com/images/201703/source_img/2553_G_1489960086616.jpg]]>
</image_default>
<intro>
<![CDATA[<p style="text-align:center;"><img title="a5891e18-3c0a-44cc-a535-22b74feab5e2.jpg" src="/images/upload/20170320/14899888792177.jpg" />
</p><p><br />
</p>]]>
</intro>
<type>
<![CDATA[国内仓库]]>
</type>
<is_shipping>0</is_shipping>
<duty_free>1</duty_free>
<brief>
<![CDATA[]]>
</brief>
<limit_num>0</limit_num>
<warehouse_id>121</warehouse_id>
<country_id>2</country_id>
<goods_link>
<![CDATA[http://www.jtgloble.com/goods.php?id=2553]]>
</goods_link>
<unit>
<![CDATA[千克]]>
</unit>
<country_abbreviation>
<![CDATA[KOR]]>
</country_abbreviation>
<warehouse>
<![CDATA[国内C1130仓]]>
</warehouse>
<img_url>
<item key="0">
<img>
<![CDATA[images/201703/goods_img/2553_P_1489960086066.jpg]]>
</img>
</item>
<item key="1">
<img>
<![CDATA[images/201703/goods_img/2553_P_1489960086382.jpg]]>
</img>
</item>
<item key="2">
<img>
<![CDATA[images/201703/goods_img/2553_P_1489960086593.jpg]]>
</img>
</item>
</img_url>
<thumb_url>
<item key="0">
<img>
<![CDATA[images/201703/thumb_img/2553_thumb_P_1489960086082.jpg]]>
</img>
</item>
<item key="1">
<img>
<![CDATA[images/201703/thumb_img/2553_thumb_P_1489960086064.jpg]]>
</img>
</item>
<item key="2">
<img>
<![CDATA[images/201703/thumb_img/2553_thumb_P_1489960086118.jpg]]>
</img>
</item>
</thumb_url>
<img_original>
<item key="0">
<img>
<![CDATA[images/201703/source_img/2553_P_1489960086462.jpg]]>
</img>
</item>
<item key="1">
<img>
<![CDATA[images/201703/source_img/2553_P_1489960086342.jpg]]>
</img>
</item>
<item key="2">
<img>
<![CDATA[images/201703/source_img/2553_P_1489960086971.jpg]]>
</img>
</item>
</img_original>
<products></products>
</data_info>
</info>
</shopex>
对应pojo:shopex.java、Info.java、ImgUrl.java
package com.docus.entity;
import lombok.Data;
import lombok.ToString;
import java.util.List;
/**
* @ProjectName:
* @Description:
* @Param 传输参数
* @Return
* @Author: 曾文和
* @CreateDate: 2020/11/24 17:23
* @UpdateUser: 曾文和
* @UpdateDate: 2020/11/24 17:23
* @UpdateRemark: 更新说明
* @Version: 1.0
*/
@Data
@ToString
public class shopex {
private String result;
private String msg;
private List<Info> info;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<Info> getInfo() {
return info;
}
public void setInfo(List<Info> info) {
this.info = info;
}
@Override
public String toString() {
return "Shopex{" +
"result='" + result + '\'' +
", msg='" + msg + '\'' +
", info=" + info +
'}';
}
}
package com.docus.entity;
import lombok.Data;
import lombok.ToString;
import java.util.LinkedList;
import java.util.List;
/**
* @ProjectName:
* @Description:
* @Param 传输参数
* @Return
* @Author: 曾文和
* @CreateDate: 2020/11/24 17:24
* @UpdateUser: 曾文和
* @UpdateDate: 2020/11/24 17:24
* @UpdateRemark: 更新说明
* @Version: 1.0
*/
@Data
@ToString
public class Info {
private String goods_id;
private String last_modify;
private String cat_id;
private String category_name;
private String brand_id;
private String brand_name;
private String price;
private String bn;
private String name;
private String marketable;
private String weight;
private String store;
private String score;
private String uptime;
private String image_default;
private String intro;
private String type;
private String is_shipping;
private String duty_free;
private String brief;
private String limit_num;
private String warehouse_id;
private String country_id;
private String goods_link;
private String unit;
private String country_abbreviation;
private String warehouse;
private List<ImgUrl> img_url;
private List<ImgUrl> thumb_url;
private List<ImgUrl> img_original;
private String products;
}
package com.docus.entity;
import lombok.Data;
import lombok.ToString;
/**
* @ProjectName:
* @Description:
* @Param 传输参数
* @Return
* @Author: 曾文和
* @CreateDate: 2020/11/24 17:50
* @UpdateUser: 曾文和
* @UpdateDate: 2020/11/24 17:50
* @UpdateRemark: 更新说明
* @Version: 1.0
*/
@Data
@ToString
public class ImgUrl {
private String img;
}
添加依赖:
<!-- https://mvnrepository.com/artifact/org.jdom/jdom2 -->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
xmlUtils工具类XmlInterfaceUtils:
package com.docus.util;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* CREATE BY OUKELE
* CREATE TIME:2020/3/17 - 9:15
*/
/**
*
* 1、实现 对象 转 xml
* 2、实现 xml 转对象
*/
public class XmlInterfaceUtils {
private XmlInterfaceUtils() {
}
/**
* 对象 转 xml
*
* @param object
* @return 返回一个生成xml的位置
*/
public static String convertToXml(Object object) {
if (object == null) {
return null;
}
Element root = null;
try {
Class<?> aClass = object.getClass();
// 根节点
root = new Element(aClass.getSimpleName());
for (Field declaredField : aClass.getDeclaredFields()) {
declaredField.setAccessible(true);
// 这个属性为 List 时
if (declaredField.getGenericType() instanceof ParameterizedType) {
Element child1 = new Element(declaredField.getName());
List<?> objList = (List<?>) declaredField.get(object);
if (objList != null) {
ListObjecToXml(objList, child1);
root.addContent(child1);
}
} else {
String fieldName = declaredField.getName();
Element child = new Element(fieldName);
child.setText(String.valueOf(declaredField.get(object)));
root.addContent(child);
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("对象转换成XML出现异常:" + e.getMessage());
}
try {
// 将 根节点 加入 文档中
Document doc = new Document(root);
// 创建xml输出流操作类
XMLOutputter xmlOutput = new XMLOutputter();
// 格式化xml内容
xmlOutput.setFormat(Format.getPrettyFormat());
File directory = new File("src/main/resources");
String courseFile = directory.getCanonicalPath();
// 把xml输出到指定位置
File f = new File(courseFile + File.separator + "temp");
if (!f.exists()) {
f.mkdirs();
}
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHssmm");
System.out.println(f.getAbsolutePath());
File file = new File(f.getAbsolutePath() + File.separator + object.getClass().getSimpleName() + format.format(new Date()) + ".xml");
xmlOutput.output(doc, new FileOutputStream(file));
System.out.println("生成完毕! " + file.getName() + "文件生成位置为:" + file.getAbsolutePath());
return file.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
System.out.println("生成xml文件出现异常:" + e.getMessage());
}
return null;
}
// 处理 List<实体> objData
private static void ListObjecToXml(List<?> objData, Element element) throws Exception {
if (objData != null) {
for (int i = 0; i < objData.size(); i++) {
Field[] declaredFields = objData.get(i).getClass().getDeclaredFields();
Object obj = objData.get(i);
Element root = new Element(obj.getClass().getSimpleName());
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
Element child = new Element(declaredField.getName());
if (declaredField.getGenericType() instanceof ParameterizedType) {
List<?> objList = (List<?>) declaredField.get(obj);
if (objList != null) {
ListObjecToXml(objList, child);
root.addContent(child);
}
} else {
child.setText(String.valueOf(declaredField.get(obj)));
root.addContent(child);
}
}
element.addContent(root);
}
}
}
/**
* xml 转 对象
*
* @param clazz
* @param xmlStr
* @return
* @throws Exception
*/
public static Object dataXmltoEntity(Class<?> clazz, String xmlStr) {
if (clazz == null) {
System.out.println("未设置对象的类型");
return null;
}
File file = new File(xmlStr);
if (!file.exists()) {
System.out.println("解析失败,找不到文件");
return null;
}
//创建Jdom2的解析器对象
SAXBuilder builder = new SAXBuilder();
Document document = null;
Element root = null;
Object obj = null;
try {
document = builder.build(file.getAbsoluteFile());
root = document.getRootElement();
if (!root.getName().equals(clazz.getSimpleName())) {
System.out.println("xml内容无法转成 " + clazz + "对象,请检查!");
return null;
}
// new出 当前最大的对象
obj = clazz.getConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
System.out.println("无法进行xml解析,请检查!");
}
try {
List<Element> children = root.getChildren();
for (Element child : children) {
// 第二层的xml数据
List<Element> children1 = child.getChildren();
if (children1.isEmpty()) { // 处理第一层的xml数据
Field field = clazz.getDeclaredField(child.getName());
field.setAccessible(true);
if (field.getGenericType().getTypeName().equals("int")) {
field.set(obj, Integer.parseInt(child.getValue()));
} else {
field.set(obj, child.getValue());
}
} else { // 处理第二层的 xml 数据
mm(clazz, obj, child, children1);
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("解析xml数据转换成实体出现异常:" + e.getMessage());
}
return obj;
}
private static void mm(Class<?> clazz, Object obj, Element child, List<Element> children1) throws Exception {
// 取到当前的 list 属性
Field field = clazz.getDeclaredField(child.getName());
field.setAccessible(true);
Class<?> genericClazz = null;
if (field.getType() == List.class) {
// 如果是List类型,得到其Generic的类型
Type genericType = field.getGenericType();
if (genericType != null) {
// 如果是泛型参数的类型
if (genericType instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) genericType;
//得到泛型里的class类型对象
genericClazz = (Class<?>) pt.getActualTypeArguments()[0];
}
}
}
if (genericClazz != null) {
List list = new ArrayList();
// list 中 包含的对象
for (Element element : children1) {
// 取出当前类的属性与值
List<Element> children2 = element.getChildren();
// new 出List中包含的对象
Object o = genericClazz.getConstructor().newInstance();
// 当前对象进行赋值
for (Element element1 : children2) {
if (element1.getChildren().isEmpty()) {
Field field1 = genericClazz.getDeclaredField(element1.getName());
field1.setAccessible(true);
field1.set(o, element1.getValue());
} else {
// 递归处理
mm(genericClazz, o, element1, element1.getChildren());
}
}
list.add(o);
}
field.set(obj, list);
}
}
}
测试代码:
package com.docus.test;
import com.docus.entity.shopex;
import com.docus.util.XmlInterfaceUtils;
import org.junit.Test;
/**
* @ProjectName:
* @Description:
* @Param 传输参数
* @Return
* @Author: 曾文和
* @CreateDate: 2020/11/24 16:00
* @UpdateUser: 曾文和
* @UpdateDate: 2020/11/24 16:00
* @UpdateRemark: 更新说明
* @Version: 1.0
*/
public class ReadXmlDataTest {
@Test
public void ReadXmlDataTest(){
//定义文件路径
String filePath = "D:\\新建文本文档.txt";
shopex shopex = new shopex();
shopex = (shopex)XmlInterfaceUtils.dataXmltoEntity(shopex.getClass(), filePath);
System.out.println(shopex);
}
}