SimpleXML 解析不适​​用于@ElementList

SimpleXML parsing not working with @ElementList

我在这个解析上苦苦挣扎了几个小时,所以我想你可能会有见解。 我得到了这个 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>。 我应该更改什么才能使其正常工作?

这样试试

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 进行适当封装(只是说说,不确定是否这样做)