<img alt="" src="https://secure.leadforensics.com/150446.png " style="display:none;">
Go to top icon

Unmarshalling XML into List of List in JAXB

Madhura Oak Sep 24, 2013

Java Unmarshalling JAXB Unmarshalling XML Technology

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>

e-Zest is a leading digital innovation partner for enterprises and technology companies that utilizes emerging technologies for creating engaging customers experiences. Being a customer-focused and technology-driven company, it always helps clients in crafting holistic business value for their software development efforts. It offers software development and consulting services for cloud computing, enterprise mobility, big data and analytics, user experience and digital commerce.