[英]SimpleXML parsing not working with @ElementList
I'm struggling with this parsing for few hours so I thought maybe you will have insights. 我在这个解析中苦苦挣扎了几个小时,所以我想也许您会有所见识。 I got this XML structure: 我得到了以下XML结构:
<ItemSearchResponse>
<OperationRequest>...</OperationRequest>
<Items>
<Request>
<IsValid>true</IsValid>
</Request>
<TotalPages>16</TotalPages>
<Item>
<DetailPageURL>http://....</DetailPageURL>
</Item>
<Item>....</Item>
...
<Item>....</Item>
</Items>
</ItemSearchResponse>
My classes are: 我的课程是:
Root(strict=false)
public class ItemSearchResponse {
@ElementList
List<Item> Items;
}
and: 和:
@Root
public class Item {
@Element(name="DetailPageURL", required = false)
private String url;
}
when I run below code: 当我运行以下代码时:
InputStream is = ... // stream from xml;
Serializer serializer = new Persister();
ItemSearchResponse response = serializer.read(ItemSearchResponse.class, is);
I get below exception: 我得到以下异常:
org.simpleframework.xml.core.ElementException: Element 'IsValid' does not have a match in class club.mymedia.shoppingadvisor.amazon.xml.Item at line 1
It seems that the parsing of <Item>
didn't work and it parsed <Request>
instead. 似乎<Item>
的解析不起作用,而是解析了<Request>
。 What should I change to make it work? 我应该更改使其工作吗?
Try like this 这样尝试
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;
}
Don't forget the java naming convention to have variables starting with lowercase, also variable names should not start with underscore _ or dollar sign $ characters. 不要忘记Java命名约定以小写字母开头的变量,变量名也不应以下划线_或美元符号$字符开头。
Also consider making the fields private and using getters for proper encapsulation as per OOP principles (just saying, not sure if you do) 还应考虑根据OOP原则将字段设置为私有并使用getter进行正确的封装(只是说,不确定是否这样做)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.