SimpleXML解析不适用于@ElementList

时间:2017-08-24 17:22:00

标签: java xml parsing exception simple-framework

我在这个解析中挣扎了几个小时,所以我想也许你会有见解。 我有这个XML结构:

<ItemSearchResponse>
     <OperationRequest>...</OperationRequest>
     <Items>
         <Request>
              <IsValid>true</IsValid>
         </Request>
         <TotalPages>16</TotalPages>
         <Item>
              <DetailPageURL>http://....</DetailPageURL>
         </Item>
          <Item>....</Item>
           ...
           <Item>....</Item>
     </Items>
</ItemSearchResponse>

我的课程是:

Root(strict=false)
public class ItemSearchResponse {

    @ElementList
    List<Item> Items;
}

和:

@Root
public class Item {
    @Element(name="DetailPageURL", required = false)
    private String url;
}

当我在代码下面运行时:

InputStream is = ... // stream from xml;
Serializer serializer = new Persister();
ItemSearchResponse response = serializer.read(ItemSearchResponse.class, is);

我得到以下异常:

org.simpleframework.xml.core.ElementException: Element 'IsValid' does not have a match in class club.mymedia.shoppingadvisor.amazon.xml.Item at line 1

似乎<Item>的解析不起作用,而是解析<Request>。 我应该改变什么才能使它发挥作用?

1 个答案:

答案 0 :(得分:1)

试试这个

import java.io.InputStream;
import java.util.List;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

class Main {

    public static void main(String[] args) throws Exception {
        Serializer serializer = new Persister();
        InputStream source = ClassLoader.getSystemResourceAsStream("myxml.xml");
        ItemSearchResponse itemSearchResponse = serializer.read(ItemSearchResponse.class, source);
    }
}

@Root
class ItemSearchResponse {
    @Element(name = "Items")
    Items items;

    @Element(name = "OperationRequest")
    String operationRequest;
}

class Items {

    @Element(name = "Request")
    Request request;

    @Element(name = "TotalPages")
    int totalPages;

    @ElementList(inline = true, name = "Item")
    List<Item> itemList;
}

class Request {

    @Element(name = "IsValid")
    boolean isValid;
}

@Root(name = "Item")
class Item {

    @Element(name = "DetailPageURL", required = false)
    String url;
}

不要忘记java命名约定,让变量以小写开头,变量名也不应该以下划线_或美元符号$字符开头。

还要考虑根据OOP原则将字段设为私有并使用getter进行适当的封装(只是说,不确定是否这样做)