转载

xml和Bean相互转换

1.引入包

<dependency> 
    <groupId>com.thoughtworks.xstream</groupId> 
    <artifactId>xstream</artifactId> 
    <version>1.4.9</version> 
</dependency>
<dependency>
   <groupId>dom4j</groupId>
   <artifactId>dom4j</artifactId>
   <version>1.6.1</version>
</dependency>

2.Java代码

import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;

/**
 * XML工具类
 */
public class XmlUtil {
 private static XStream xStream = new XStream();
 /**
 * 解析xml
 * @param xml xml字符串
 * @param elementName 要解析的父标签
 * @param cls 目标类型
 * @return 解析结果
 */
 public static <T> T xmlToBean(String xml, String elementName, Class<T> cls) {
 T object = null;
 try {
 Document document = DocumentHelper.parseText(xml);
 //如果不是SOAP返回的报文,是XML字符串则不需要这行代码
 String beanXml = document.getRootElement().element("Body").element(
 elementName).asXML();
 xStream.alias(elementName, cls);
 object = (T) xStream.fromXML(beanXml);
 } catch (Exception e) {
 e.printStackTrace();
 }
 return object;
 }

 /**
 * 转换XML
 * 对象添加 @XStreamAlias("标签名称")
 * 集合添加 @XStreamImplicit(itemFieldName="标签名称")
 * 否则会出现解析的xml中标签带类全称现象
 * @param object 要转换的对象
 * @return 结果字符串
 */
 public static String beanToXml(Object object) {
 xStream.processAnnotations(object.getClass()); // 应用注解
 xStream.autodetectAnnotations(true); //自动检测注解
 return xStream.toXML(object);
 }
}

3.验证

public static void main(String[] args) {
    String json ="";
    List<T> packages =  new ArrayList<T>();
    packages = JSONObject.parseObject(json,new TypeReference<List<T>>() {});
    xStream.alias("res", List.class);
    String xml = XmlUtil.beanToXml(packages);
    System.out.println("xml:"+xml);
}
 
正文到此结束
Loading...