简体   繁体   中英

Parsing nested tags with XStream

I'm using a database API called Socrata to parse information for recycling services. An example of the XML output from this service can be found here:

http://www.datakc.org/api/views/zqwi-c5q3/rows.xml?search=%22computer%22

As you can probably tell, this seems just like bad XML . The problem I'm having is that the tag containing the list of rows is called row (with no attributes) and each row is also called row (with attributes). This seems like it will confuse the hell out of XStream, and I cannot find a way at all to handle this data with XStream.

Any of you XStream/XML gurus out there know what I can do?

The solution wasn't very intuitive but I managed to figure it out. First I had to declare a class that represented the response tag. This class also contains a container of a list of recycle services. Here's how the class looks:

@XStreamAlias("response")
public class QueryResponse {

    @XStreamAlias("row")
    private RecycleServices services;

    public RecycleServices getServices() {
        return services;
    }

    public void setServices(RecycleServices services) {
        this.services = services;
    }

}

The RecycleServices class is the real trick here, which wraps an implicit List of RecycleService classes.

@XStreamAlias("row")
public class RecycleServices {

    @XStreamImplicit(itemFieldName = "row")
    private List<RecycleService> services = new ArrayList<RecycleService>();

    public List<RecycleService> getServices() {
        return services;
    }

    public void setServices(List<RecycleService> services) {
        this.services = services;
    }

}

The RecycleService class was then just a straight representation of each recycle service row, and is not really relevant to the answer of this question. I had some frustration figuring this out and I hope that this helps someone out there.

这不是解决方案,而是解决方法,但是通过使用XSLT将DOM重写为XStream能够更好使用的东西,行/元素命名将是可克服的。

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