At times you would need to unmarshal XML in List<List<T>> using JAXB. The XML in Listing 1 has multiple <SkillSet> elements. Each <SkillSet> element has multiple <Skill> elements. This XML can be unmarshalled in a List<List<String>> where each <SkillSet> would represent an element in the outer list and each <Skill> represents an element in the inner List.
<SkillSets> <SkillSet> <Skill>Java</Skill> <Skill>XML</Skill> <Skill>UML</Skill> </SkillSet> <SkillSet> <Skill>Java</Skill> <Skill>Database Design</Skill> </SkillSet> </SkillSets>
Listing 1. A sample XML
The Java classes used in this example are given below in Listing 2 and 3.
@XmlRootElement(name="SkillSets") public class SkillSets { private List<SkillSet> skills = new ArrayList<SkillSet>(); @XmlElement(name="SkillSet") public List<SkillSet> getSkills() { return skills; } public void setSkills(List<SkillSet> skills) { this.skills = skills; } }
Listing 2. The SkillSets class
public class SkillSet { private List<String> skills = new ArrayList<String>(); @XmlElement(name="Skill") public List<String> getSkills() { return skills; } public void setSkills(List<String> skills) { this.skills = skills; } } }
Listing 3. The SkillSet class
The code in Listing 4 is used for unmarshalling.
JAXBContext context = JAXBContext.newInstance(SkillSets.class); Unmarshaller unmarshaller = context.createUnmarshaller(); //use appropriate argument in unmarshal method SkillSets skillsets = (SkillSets)unmarshaller.unmarshal(...);
Listing 4. Unmarshalling the XML
The code in Listing 5 can be used to create a List<List>.
List<List<String>> skillsetsList = new ArrayList<List<String>>(); for(SkillSet skillset : skillsets.getSkills()) { List<String> skills = new ArrayList<String>(); skillsetsList.add(skills); skills.addAll(skillset.getSkills()); } System.out.println(skillsetsList); //prints [[Java, XML, UML], [Java, Database Design]]
Listing 5. Creating List<List>