简体   繁体   中英

Deserialize inline elementlist directly into a List

I have the following XML structure:

<keys>
   <key>
      <tag>
         someValue
      </tag>
   </key>
   <key>
      <tag>
         someValue
      </tag>
   </key>
</keys>

The key element is represented in code in the following class:

public class Key {

    @Element(name = "tag")
    private String tag;
}

My goal is to deserialize these directly into a List , something like this:

Serializer serializer = new Persister();
List<Key> list = serializer.read(Key.class, inputStream); // pseudo code

How can i achieve this with Simple ?

Use the @ElementList annotation like so

@Root(name="keys")
public class KeyList {

    @ElementList(inline=true, entry="key")
    private List<Key> keys;

    public List<Key> getKeys() {
       return keys;
    }
}

Then

Persister persister = new Persister();
List<Key> keys = persister.read(KeyList.class, source).getKeys();

I would recommend using JAXB (Java Architecture for XML Binding)

Here's a link to a couple of tutorials:

They can explain it better than me. But basically you use annotations defined in the javax.xml.bind.annotation package which define your xml structure. Then create a simple JAXB Handler class to handle marshaling and unmarshaling.

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