Xml2Object

         <dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
            <version>1.4.4</version>
        </dependency>
<?xml version="1.0" encoding="UTF-8"?>
<com.yundaex.wms.core.store.po.RivQuant>
  <qtId>-1</qtId>
  <qtAllocQty>100</qtAllocQty>
  <qtBillId>25</qtBillId>
  <qtBillType>1</qtBillType>
  <qtContainerId>11</qtContainerId>
  <qtContainerTypeId>19</qtContainerTypeId>
  <qtLocationId>10</qtLocationId>
  <qtLotItem1>22</qtLotItem1>
  <qtLotItem2>12</qtLotItem2>
  <qtLotItem3>12</qtLotItem3>
  <qtLotNo></qtLotNo>
  <qtLotString1></qtLotString1>
  <qtLotString2></qtLotString2>
  <qtLotString3></qtLotString3>
  <qtLotString4></qtLotString4>
  <qtLotString5></qtLotString5>
  <qtLpn></qtLpn>
  <qtMaterialId>17</qtMaterialId>
  <qtMaterialStatusId>8</qtMaterialStatusId>
  <qtOnhandQty>100</qtOnhandQty>
  <qtOnrecvQty>100</qtOnrecvQty>
  <qtOrgId>49</qtOrgId>
  <qtOwnerId>19</qtOwnerId>
  <qtTrolleyCellNo></qtTrolleyCellNo>
  <qtType>location</qtType>
  <qtVoucherNo>123456</qtVoucherNo>
  <versionNumber>0</versionNumber>
</com.yundaex.wms.core.store.po.RivQuant>
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.lang.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.thoughtworks.xstream.XStream;


public class Xml2Object {

    private static XStream xstream;

    static {
        xstream = new XStream();
    }

    public static Object convert2Object(String xmlName) {
        String configPath = "classpath*:data/"+xmlName;
        //String path = Xml2Object.class.getResource("/").getPath() + xmlName;
        InputStream inputStream = null;
        try {
             final int index = StringUtils.lastIndexOf(configPath, ":") == -1 ? 0 : StringUtils.lastIndexOf(configPath, ":");
             final Resource resource = new ClassPathResource(StringUtils.substring(configPath, index+1, configPath.length()));
             inputStream = resource.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Object obj = xstream.fromXML(inputStream);
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return obj;
    }

    public static void main(String[] args) {
        convert2Object("owner.xml");
    }
}

 

posted @ 2017-06-15 14:25  tonggc1668  阅读(392)  评论(0编辑  收藏  举报