xml作为数据传输的常见格式,有必要对其应用场景熟练掌握和使用
1.jaxB与xml互转
关键注解:
@XmlRootElement(name="") :标记根标签,并将name对的值和class的名称实现相互转化
@XmlAccessorType(XmlAccessType.FIELD) @XmlElement(name=""):标记字段,name对的值和被注解的字段可以相互转换
2.XStream与xml互转
关键注解:
@XStreamAlias(""):通用注解,value对应值的标签和被注解的字段可以相互转换。
3.工具类:
package com.sf.escs.util;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringBufferInputStream;
import java.io.StringReader;
import java.io.StringWriter;
/**
* @Auther nick
* @Date: 2024/3/8 14:00
*/
public class XmlUtil {
/**
* xstream
*
* @param o
* @return
*/
public static String objectToXmlStringByXStream(Object o) {
String xmlString = "";
XStream xStream = new XStream();
xStream.processAnnotations(o.getClass());
xmlString = xStream.toXML(o);
return xmlString;
}
public static String objectToXmlStringByJaxb(Object o) {
String xmlString = "";
try {
JAXBContext jaxbContext = JAXBContext.newInstance(o.getClass());
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter stringWriter = new StringWriter();
marshaller.marshal(o, stringWriter);
xmlString = stringWriter.toString();
} catch (JAXBException e) {
e.printStackTrace();
}
return xmlString;
}
public static <T> T xmlStringToObjectByXStream(String xmlStr, Class<T> tClass) {
XStream xStream = new XStream(new DomDriver());
xStream.processAnnotations(tClass);
Object o = xStream.fromXML(xmlStr);
return convert(o, tClass);
}
public static <T> T xmlStringToObjectByJAXB(String xmlStr, Class<T> tClass) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(tClass);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Object unmarshal = unmarshaller.unmarshal(new StringReader(xmlStr));
return convert(unmarshal, tClass);
} catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
/**
* @param obj 具体类型,object中子类
* @param clazz class
* @param <T> 泛型
* @return 转换泛型
* @description 解决强制类型转换泛型警告问题
*/
public static <T> T convert(Object obj, Class<T> clazz) {
if (clazz.isInstance(obj)) {
return clazz.cast(obj);
} else {
return null;
}
}
public static void main(String[] args) {
}
}