简体   繁体   中英

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:

<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. 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.

Also consider making the fields private and using getters for proper encapsulation as per OOP principles (just saying, not sure if you do)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM