Xml解析和工具类的使用
前言
Github:https://github.com/HealerJean
1 、解释
1.1、@JacksonXmlRootElement
指定生成xml根标签的名字;
1.2、@JacksonXmlProperty
指定包装标签名,或者指定标签内部属性名;
1.3、@JacksonXmlElementWrapper
用于指定List等集合类,外围标签名;用在非集合类上无效
1.4、@JacksonXmlText:
指定当前这个值,没有xml标签包裹。
2、测试
2.1、测试DTO
package com.healerjean.proj.a_test.xml;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlText;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.List;
/**
* @author HealerJean
* @ClassName Group
* @date 2019/10/29 22:20.
* @Description
*/
@Data
// @JacksonXmlRootElement:指定生成xml根标签的名字;
@JacksonXmlRootElement(localName = "Class")
public class Group {
private Teacher teacher;
// @JacksonXmlElementWrapper:可用于指定List等集合类,外围标签名;
@JacksonXmlElementWrapper(localName = "Students")
// @JacksonXmlProperty:指定包装标签名,或者指定标签内部属性名;
@JacksonXmlProperty(localName = "Stu")
private List<Student> student;
@Data
@AllArgsConstructor
public static class TeacherType {
@JacksonXmlProperty(isAttribute = true, localName = "type")
private String type;
//@JacksonXmlText:指定当前这个值,没有xml标签包裹。
// 这个值意义在于,一般这个值所在的类只有这一个正常属性,或者其他属性全部为 @JacksonXmlProperty(isAttribute = true,
@JacksonXmlText
private String grade;
}
@Data
public static class Teacher {
@JacksonXmlProperty(localName = "TypeCode")
private TeacherType teacherTypeCode;
private String name;
}
@Data
public static class Student {
@JacksonXmlProperty(isAttribute = true, localName = "stu_id")
private String id;
private String name;
private Integer age;
}
}
2.2、测试类
@Test
public void test() {
Group group = new Group();
Group.Teacher teacher = new Teacher();
teacher.setTeacherTypeCode(new TeacherType("语文老师", "A"));
teacher.setName("马老师");
group.setTeacher(teacher);
Student student = new Student();
student.setId("001");
student.setName("HealerJean");
student.setAge(25);
group.setStudent(Arrays.asList(student));
String xml = XmlUtils.toXml(group);
log.info("数据原文:【 {} 】", xml);
}
//XML标签名:使用骆驼命名的属性名,
xmlMapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
<Class>
<Teacher>
<Name>马老师</Name>
<TypeCode type="语文老师">A</TypeCode>
</Teacher>
<Students>
<Stu stu_id="001">
<Name>HealerJean</Name>
<Age>25</Age>
</Stu>
</Students>
</Class>
自定义的转化转大写并加下划线,强制命令的不可以,比如下面的Class是强制命名的
xmlMapper.setPropertyNamingStrategy(new UpperCaseSnackNamingStrategy());
<Class>
<TEACHER>
<NAME>马老师</NAME>
<TypeCode type="语文老师">A</TypeCode>
</TEACHER>
<Students>
<Stu stu_id="001">
<NAME>HealerJean</NAME>
<AGE>25</AGE>
</Stu>
</Students>
</Class>
3、工具类
3.1、XmlUtils
package com.healerjean.proj.util.xml;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.healerjean.proj.util.xml.strategy.UpperCaseSnackNamingStrategy;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
@Slf4j
public class XmlUtils {
public static final XmlMapper xmlMapper;
static {
xmlMapper = new XmlMapper();
SimpleModule module = new SimpleModule();
xmlMapper.registerModule(module);
xmlMapper.setDefaultUseWrapper(false);
//字段为null,自动忽略,不再序列化
xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//XML标签名:使用骆驼命名的属性名,
// xmlMapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
//转化成加下划线和大写
xmlMapper.setPropertyNamingStrategy(new UpperCaseSnackNamingStrategy());
//设置转换模式
xmlMapper.enable(MapperFeature.USE_STD_BEAN_NAMING);
}
public static String toXml(Object object) {
try {
return xmlMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
log.error("Xml转换失败", e);
throw new RuntimeException("Xml转换失败", e);
}
}
public static <T> T toObject(String xml, Class<T> c) {
try {
return xmlMapper.readValue(xml, c);
} catch (IOException e) {
log.error("Xml转换失败", e);
throw new RuntimeException("Xml转换失败", e);
}
}
}
3.2、转大写并加下划线
package com.healerjean.proj.util.xml.strategy;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
/**
* @author HealerJean
* @version 1.0v
* @ClassName UpperCaseSnackNamingStrategy
* @Date 2019/10/29 22:48.
* @Description 转大写并加下划线
*/
public class UpperCaseSnackNamingStrategy extends PropertyNamingStrategy.PropertyNamingStrategyBase {
@Override
public String translate(String input) {
if (input == null) {
return input;
}
int length = input.length();
StringBuilder result = new StringBuilder(length * 2);
int resultLength = 0;
boolean wasPrevTranslated = false;
for (int i = 0; i < length; i++) {
char c = input.charAt(i);
if (i > 0 || c != '_') {
if (Character.isUpperCase(c)) {
if (!wasPrevTranslated && resultLength > 0 && result.charAt(resultLength - 1) != '_') {
result.append('_');
resultLength++;
}
wasPrevTranslated = true;
} else {
wasPrevTranslated = false;
}
c = Character.toUpperCase(c);
result.append(c);
resultLength++;
}
}
return resultLength > 0 ? result.toString() : input;
}
}