使用xstream进行XML解析

时间:2011-06-21 17:30:33

标签: xml xstream

我有以下XML结构,我正在解析下面提到的类:

<?xml version="1.0" encoding="utf-16"?>
<OrderDiscount xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Status>Failed</Status>
  <Errors>Error : Customer 00000037 not found : Product 51 D0003 not found</Errors>
  <DeliveryID>00000037</DeliveryID>
  <CarriageAmount>0</CarriageAmount>
  <TotalDiscount>0</TotalDiscount>
  <OrderLines>
    <Warehouse>51</Warehouse>
    <Product>D0003</Product>
    <ContractPrice>N</ContractPrice>
    <UnitOfSale>20</UnitOfSale>
    <Ordered>1</Ordered>
    <ListPrice>10</ListPrice>
    <NetPrice>10</NetPrice>
    <NewNetPrice>0</NewNetPrice>
  </OrderLines>
</OrderDiscount>

在这里,我们可以有<OrderLines>的多个实例。我试图使用以下2个类来解析它

import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;

/**
 * @author nka
 *
 */

@XStreamAlias("OrderDiscount")
public class OrderDiscount {


    @XStreamAlias("Status")
    private String Status;

    @XStreamAlias("Errors")
    private String Errors;

    @XStreamAlias("DeliveryID")
    private String DeliveryID;

    @XStreamAlias("CarriageAmount")
    private String CarriageAmount;

    @XStreamAlias("TotalDiscount")
    private String TotalDiscount;

    @XStreamAlias("OrderLines")
    private List<OrderLines> OrderLines;

}

第二课:

public class OrderLines {

    @XStreamAlias("Warehouse")
    private String Warehouse;

    @XStreamAlias("Product")
    private String Product;

    @XStreamAlias("ContractPrice")
    private String ContractPrice;

    @XStreamAlias("UnitOfSale")
    private String UnitOfSale;

    @XStreamAlias("Ordered")
    private String Ordered;

    @XStreamAlias("ListPrice")
    private String ListPrice;

    @XStreamAlias("NetPrice")
    private String NetPrice;

    @XStreamAlias("NewNetPrice")
    private String NewNetPrice;
}

我使用以下代码来解析它:

    OrderDiscount orderDiscount = null;

    final XStream xstream = new XStream(new StaxDriver());
    xstream.processAnnotations(OrderDiscount.class);
    xstream.processAnnotations(OrderLines.class);

    orderDiscount = (OrderDiscount) xstream.fromXML(response);

我收到以下错误:

Target exception: com.thoughtworks.xstream.converters.ConversionException: Warehouse : Warehouse : Warehouse : Warehouse
---- Debugging information ----
message             : Warehouse : Warehouse
cause-exception     : com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message       : Warehouse : Warehouse
class               : uk.co.portaltech.quicklive.thirdparty.datel.OrderDiscount
required-type       : java.util.ArrayList
path                : /OrderDiscount/OrderLines/Warehouse
line number         : 1
-------------------------------

有人可以帮我纠正我的Java OBJECTS的结构来解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

你可以使用  用于XML解析的自定义处理程序,以更通用的方式,以便它可以根据注释解析所有pojo类