Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Map a class Order with a List<Line> lines so that the XML looks like <order><lines><line>...</line><line>...</line></lines></order>. What changes if you drop the wrapper element?

We annotate the list with @XmlElementWrapper(name = "lines") and @XmlElement(name = "line"), and initialise it with new ArrayList<>(), which produces <order><lines><line>...</line></lines></order>. Without @XmlElementWrapper, each item is written directly under <order> as a repeated <line> element. The wrapper also lets a document tell 'no list' from 'empty list', a null list writes no wrapper while an empty one writes <lines/>, so we decide and document which we produce, and for lists of simple values @XmlList packs them into one space-separated element.

Why this question is asked

Lists are where XML formats differ most, and partner schemas are strict about them: some wrap repeated elements in a container, some repeat them directly, and some put simple values in one element. Getting it wrong gives a document that looks almost right and is rejected. Interviewers ask this coding question because it is short to answer but has a few details that show real experience: list initialisation, the null versus empty distinction, and @XmlList. In this answer, we will write the mapping with a wrapper, see what changes without it, look at how JAXB fills lists when reading, decide how to handle empty lists, and finish with lists of simple values.

1A Quick Recap: How JAXB Maps a Collection

When JAXB meets a collection property, such as a List, it does not write the list itself as an element. It writes one element per item, each named after the property or after @XmlElement(name). The question is only what surrounds those elements. XML Schema expresses this with maxOccurs="unbounded" on the repeated element, either directly inside the parent's sequence, or inside a separate container element.

2Mapping With a Wrapper Element

Here are the classes for the shape in the question. @XmlElementWrapper adds the container element, and @XmlElement names each item inside it.

Java
@XmlRootElement(name = "order")
@XmlAccessorType(XmlAccessType.FIELD)
public class Order {
@XmlAttribute private String id;
@XmlElementWrapper(name = "lines")
@XmlElement(name = "line")
private List<Line> lines = new ArrayList<>();
public List<Line> getLines() { return lines; }
}
@XmlAccessorType(XmlAccessType.FIELD)
public class Line {
@XmlAttribute private String sku;
@XmlAttribute private int qty;
Line() {}
Line(String sku, int qty) { this.sku = sku; this.qty = qty; }
}
Order o = new Order("A-17");
o.getLines().add(new Line("PEN", 3));
o.getLines().add(new Line("INK", 1));
// <order id="A-17">
// <lines>
// <line sku="PEN" qty="3"/>
// <line sku="INK" qty="1"/>
// </lines>
// </order>

Without @XmlElement(name = "line"), each item would be named after the field, so we would get <lines><lines>...</lines></lines>, which is a common mistake. The two annotations always work as a pair: the wrapper names the container and @XmlElement names the items.

3Dropping the Wrapper

If we remove @XmlElementWrapper and keep @XmlElement(name = "line"), JAXB writes the items directly inside <order>. The Java code does not change at all; only the XML does.

Java
@XmlElement(name = "line")
private List<Line> lines = new ArrayList<>();
// <order id="A-17">
// <line sku="PEN" qty="3"/>
// <line sku="INK" qty="1"/>
// </order>
Same Java list, two XML shapes
MappingXML for two linesEmpty listNull list
@XmlElementWrapper + @XmlElement<lines><line/><line/></lines><lines/>nothing written
@XmlElement only<line/><line/>nothing writtennothing written
Only the wrapped form can show the difference between an empty and a missing list.

Both shapes are common. The wrapped form groups the items, which makes documents easier to read when an order has several lists, such as lines and discounts. The unwrapped form is shorter and is what xjc generates for a plain repeated element in a schema. Since the partner's schema decides, we simply match it, and a schema validation test catches the wrong choice immediately.

4How JAXB Fills the List When Reading

When unmarshalling, JAXB reads each <line> and adds it to the list. If the list field is null, it creates a new list first. If the list already exists, because we initialised it, JAXB adds to that existing list. With property access, it gets the list through the getter and adds to it, which means a getter-only list works: no setter is needed, as long as the getter returns the real, mutable list.

That is why initialising with new ArrayList<>() is the safe habit. It works the same for every access type, it means code that reads the order never meets a null list, and it avoids a trap: a getter that returns an unmodifiable copy such as List.copyOf(lines) would make JAXB's add() fail with UnsupportedOperationException when unmarshalling, so for property access the getter must return the live list.

5Empty Versus Missing: Deciding What We Produce

With a wrapper, a document can say three different things: the wrapper is absent, the wrapper is present and empty, or the wrapper holds items. Some partners give the first two different meanings, for example 'lines not sent, keep the existing ones' versus 'no lines, remove them all'. JAXB writes no wrapper for a null list and an empty <lines/> for an empty list, so on output we control it by choosing null or empty.

Java
order.lines = null; // marshal: <order id="A-17"/>
order.lines = new ArrayList<>(); // marshal: <order id="A-17"><lines/></order>
// Reading back, with the field initialised to new ArrayList<>():
// <order id="A-17"/> -> lines is empty (our initial list, untouched)
// <order id="A-17"><lines/></order> -> lines is empty
// Both read as an empty list: the difference is lost

Notice the problem on input. Because we initialised the field, an absent wrapper and an empty wrapper both leave us with an empty list. If the difference matters for this partner, we leave the field uninitialised so an absent wrapper stays null and an empty one becomes an empty list. Exactly how runtimes treat an empty wrapper can differ, so we test it with our runtime. If the partner uses xsi:nil for a missing list, @XmlElementWrapper(nillable = true) writes <lines xsi:nil="true"/> for null. Whatever we choose, we write it down in the integration's documentation, because the next developer cannot guess it from the code.

6Lists of Simple Values With @XmlList

For a list of simple values, such as tags or codes, XML Schema has a list type: one element whose text holds the values separated by spaces. @XmlList maps a collection to that form.

Java
@XmlList
@XmlElement(name = "tags")
private List<String> tags = List.of("gift", "fragile", "express");
// <tags>gift fragile express</tags>
// Reading "<tags> gift fragile </tags>" gives [gift, fragile] (split on whitespace)

Because the separator is whitespace, @XmlList only works for values that can never contain spaces, such as codes, numbers and identifiers. A tag like 'next day' would be split into two values, so for free text we use repeated elements instead.

7Follow-up questions

Can I use a Set or an array instead of a List?

Yes. JAXB maps any Collection and arrays the same way. A Set loses order and duplicates, so use LinkedHashSet if order matters, and remember that a partner schema with maxOccurs allows duplicates the Set would drop.

How do I map a list of different subtypes, such as several kinds of line?

Use @XmlElements with one @XmlElement per subtype, each with its own name and type, for example productLine and serviceLine. JAXB then writes each item with the element name of its class and creates the right class when reading.

Why does my list come back with duplicated items?

Usually because both a field and a getter are mapped under the default PUBLIC_MEMBER access type, or because the getter returns a new list each time and the code merges results. Setting @XmlAccessorType(XmlAccessType.FIELD) and returning the live list fixes both.

8Conclusion

In this answer, we mapped a List<Line> with @XmlElementWrapper(name = "lines") and @XmlElement(name = "line") to produce a wrapped list, and saw that without the wrapper the items repeat directly under <order>. We saw that JAXB adds to an existing list when reading, so initialising the list is the safe default, that a wrapper can distinguish a missing list from an empty one while an initialised field hides that difference on input, and that @XmlList packs simple values into one space-separated element.

What to say in the interviewAbout 80 seconds aloud

Open with

I would put two annotations on the field: @XmlElementWrapper with name lines, which creates the container element, and @XmlElement with name line, which names each item, and initialise the field with a new ArrayList.

Then, if they want more

That gives order, then lines, then one line element per item. If I drop the wrapper, the Java stays the same but each line is written directly under order as a repeated element, which is also what xjc generates for a plain repeated schema element; I match whatever the partner's schema says and validate against it in tests.

When reading, JAXB adds to the existing list, or through the getter with property access, so initialising it means callers never see null, and the getter must return the live, mutable list.

One subtle point is empty versus missing: with a wrapper, a null list writes nothing and an empty list writes an empty lines element, but if I initialise the field, both an absent and an empty wrapper read back as an empty list.

If the partner gives those different meanings, I leave the field null by default, test my runtime, and document the behaviour. Finally, for simple values like codes, @XmlList writes them in one element separated by spaces, which only works for values without spaces.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Map a class Order with a List<Line> lines so that the XML looks like...": https://scrivio-interview-library.netlify.app/java/jaxb/a96fb33aa0/