- import java.io.ByteArrayInputStream;
- import org.apache.axiom.om.OMElement;
- import org.apache.axiom.om.impl.builder.StAXOMBuilder;
- import org.apache.axis2.databinding.utils.BeanUtil;
- import org.apache.axis2.engine.DefaultObjectSupplier;
- import org.dom4j.Document;
- import org.dom4j.DocumentHelper;
- public class XMLUtil
- {
- /**
- *
- * @author : zKF27092
- * @version : 1.0
- * <p>时间 : 2010-12-15</p>
- * <p>描述 : 将XML字符串转换成对象</p>
- * <p>实现方法:将XML字符串转换成对象</p>
- * <p>Copyright 1988-2005, Huawei Tech. Co., Ltd.</p>
- * @param <T>
- * @param xml XML字符串
- * @param cls 返回类型
- * @return
- */
- @SuppressWarnings("unchecked")
- public static <T> T xmlToBean(String xml, Class<T> cls)
- {
- T object = null;
- try
- {
- OMElement omElement = new StAXOMBuilder(new ByteArrayInputStream(
- xml.getBytes("UTF-8"))).getDocumentElement();
- object = (T) BeanUtil.processObject(omElement, cls, null, true,
- new DefaultObjectSupplier());
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- return object;
- }
- /**
- *
- * @author : zKF27092
- * @version: 1.0
- * <p>时间 : 2010-12-15</p>
- * <p>描述 : 将soap返回报文转换成对象</p>
- * <p>实现方法:将soap返回报文转换成对象</p>
- * <p>Copyright 1988-2005, Huawei Tech. Co., Ltd.</p>
- * @param <T>
- * @param xml XML字符串
- * @param elementName 对象XML根元素的名称
- * @param cls 返回类型
- * @return
- */
- @SuppressWarnings("unchecked")
- public static <T> T xmlToBean(String xml, String elementName, Class<T> cls)
- {
- T object = null;
- try
- {
- Document document = DocumentHelper.parseText(xml);
- String beanXml = document.getRootElement().element("Body").element(
- elementName).asXML();
- OMElement omElement = new StAXOMBuilder(new ByteArrayInputStream(
- beanXml.getBytes("UTF-8"))).getDocumentElement();
- object = (T) BeanUtil.processObject(omElement, cls, null, true,
- new DefaultObjectSupplier());
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- return object;
- }
- }
转载于:https://my.oschina.net/phoebus789/blog/536019