1.场景描述
将javabean对象转换为xml字符串,将xml字符串转换为javabean对象。
2.maven依赖
<dependency>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.7.0</version>
</dependency>
3.注解说明
@XmlRootElement 将类或枚举类型映射到 XML 元素。
@XmlElement 将 JavaBean 属性映射到派生于属性名称的 XML 元素。
@XmlTransient 阻止将 JavaBean 属性映射到 XML 表示形式。
@XmlTransient 注释对于解决 JavaBean 属性名称与字段名称之间的名称冲突,或者用于防止字段/属性的映射。当取消首字母大写的 JavaBean 属性名称与字段名称相同时,就可能发生名称冲突。如果 JavaBean 属性引用该字段,那么可以通过防止映射使用 @XmlTransient 注释的字段或 JavaBean 属性来解决名称冲突。
4.代码编写
工具类
import org.apache.commons.beanutils.BeanUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource; import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List; /**
* xml与bean互转工具类
*/
public class JaXmlBeanUtil { /**
* 将javaBean转换为xml对象
* @param clazz
* @param bean
* @return
*/
public static String parseBeanToXml(Class clazz,Object bean){
StringWriter sw = null;
try {
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
sw = new StringWriter();
//该值默认为false,true则不会创建即头信息,即<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
jaxbMarshaller.marshal(bean, sw);
} catch (JAXBException e) {
e.printStackTrace();
}
return sw.toString();
} /**
*将xml对象转换为javaBean
* @param clazz
* @param xml
* @return
*/
public static Object parseXmlToBean(Class clazz,String xml){
if(xml!=null&&xml!=""){
Field[] fields = clazz.getDeclaredFields();
List<Field> fieldList = new ArrayList<Field>();
for (Field fie : fields) {
if (fie.isAnnotationPresent(XmlElementAnno.class)) {
fieldList.add(fie);
}
}
try {
StringReader read = new StringReader(xml);
InputSource source = new InputSource(read);
//创建一个新的SAXBuilder
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(source);
//取的根元素
Element root = doc.getRootElement();
Object object = clazz.newInstance();
if(!fieldList.isEmpty()){
for (Field field : fieldList) {
Element child = root.getChild(field.getName());
if(child!=null){
BeanUtils.setProperty(object, field.getName(), child.getValue());
}
}
}
return object;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
}
javabean对象
import com.bestpay.ecurrency.utils.XmlElementAnno; import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient; @XmlRootElement(name="root")
public class JaBeanToXml { @XmlElement(name="xmlname")
@XmlElementAnno
private String name; @XmlElement(name="xmladdress")
@XmlElementAnno
private String address; @XmlElement(name="xmlage")
@XmlElementAnno
private int age; @XmlTransient
public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} @XmlTransient
public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} @XmlTransient
public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} @Override
public String toString() {
return "JaBeanToXml{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
", age=" + age +
'}';
}
}
自定义注解,用于指定那类属性进行转换
import java.lang.annotation.*; @Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface XmlElementAnno { }
测试类
import com.bestpay.ecurrency.pojo.JaBeanToXml;
import com.bestpay.ecurrency.utils.JaXmlBeanUtil;
import org.junit.Test; public class JaBeanToXmlTest {
/**
* xml转javaBean
*/
@Test
public void parseXmlToJaBean() {
//组装xml
StringBuilder sb = new StringBuilder();
sb.append("<root>");
sb.append("<name>wangkecheng</name>");
sb.append("<address>上海</address>");
sb.append("<age>27</age>");
sb.append("</root>"); JaBeanToXml jaBeanToXml = (JaBeanToXml) JaXmlBeanUtil.parseXmlToBean(JaBeanToXml.class,sb.toString());
System.out.println(jaBeanToXml.toString());
} /**
* bean转xml
*/
@Test
public void parseJaBeanToXml(){ JaBeanToXml jaBeanToXml = new JaBeanToXml();
jaBeanToXml.setName("wangkecheng");
jaBeanToXml.setAddress("上海");
jaBeanToXml.setAge(28); String xml = JaXmlBeanUtil.parseBeanToXml(JaBeanToXml.class,jaBeanToXml);
System.out.println(xml);
}
}
测试结果
测试1:
JaBeanToXml{name='wangkecheng', address='上海', age=27}
测试2:
<root><xmlname>wangkecheng</xmlname><xmladdress>上海</xmladdress><xmlage>28</xmlage></root>
源码仓库地址:https://github.com/nn-kc/utils.git