Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Validate incoming XML against an order.xsd while unmarshalling with JAXB, and collect all errors instead of failing on the first.

We compile the XSD once with SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(...), set it on the unmarshaller with setSchema(schema), and install a ValidationEventHandler that records each event and returns true so unmarshalling continues, which collects every error instead of stopping at the first. Without a schema JAXB is lenient and lets invalid data pass silently. We harden the factories against XXE by setting ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_SCHEMA to empty, and we reuse the compiled Schema, which is thread-safe.

Why this question is asked

When a partner sends a document with three problems, telling them about the first one, waiting for a corrected file, and then telling them about the second, wastes days. Collecting all validation errors in one pass is what partners and support teams actually need. Interviewers ask this question because it combines several details people get wrong: JAXB's default leniency, how event handlers decide whether to continue, the thread safety of Schema, and XXE settings on the schema factory. In this answer, we will see what JAXB does without validation, compile and attach the schema, collect every error with a handler, harden the parsing, and package it as a reusable component.

1Why JAXB Needs a Schema to Catch Errors

JAXB maps what it recognises and ignores the rest. An element it has no mapping for is skipped, a missing required element simply leaves a field null, and elements in the wrong order are usually accepted. That leniency is convenient, but it means an invalid document can produce an object that looks fine and is wrong.

Java
String xml = """
<order xmlns="urn:acme:order">
<id>A-17</id>
<quantity>-3</quantity>
<colour>red</colour>
</order>
""";
Order o = (Order) ctx.createUnmarshaller().unmarshal(new StringReader(xml));
// no exception
// o.getQuantity() == -3 although the XSD says positiveInteger
// <colour> silently ignored although the XSD does not allow it
// o.getCustomer() == null although the XSD says customer is required

The XSD, the XML Schema Definition, already describes every one of these rules: required elements, allowed elements, value ranges and order. So instead of re-implementing them in Java, we ask JAXB to validate against the schema while it unmarshals.

2Compiling the Schema and Attaching It

SchemaFactory compiles an XSD into a Schema object. Compiling parses and checks the whole schema, including any files it imports or includes, so it is expensive; the resulting Schema is immutable and thread-safe, so we compile it once and share it. Each unmarshaller then gets the shared schema with setSchema().

Java
private static final Schema ORDER_SCHEMA = compile("/xsd/order.xsd");
static Schema compile(String resource) {
try {
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
sf.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // no DTDs fetched while compiling
sf.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); // no remote imports (see below)
URL xsd = OrderReader.class.getResource(resource);
return sf.newSchema(xsd); // a URL keeps relative includes resolvable
} catch (SAXException e) {
throw new IllegalStateException("invalid schema " + resource, e);
}
}

Two details here are worth noticing. We pass a URL rather than a bare InputStream. With newSchema(new StreamSource(xsdStream)), as often written, the schema has no location, so an xs:include of common.xsd next to it cannot be found; giving a URL, or a StreamSource with a system id, fixes that. And the ACCESS_EXTERNAL_SCHEMA setting of an empty string blocks every external schema location, which is safest when order.xsd is self-contained. If it includes local files, we allow only the protocols we need, for example "file,jar:file" for schemas inside our own jar, and never http.

3Collecting Every Error With an Event Handler

When the unmarshaller has a schema, every violation is reported as a ValidationEvent to its ValidationEventHandler. The handler's return value decides what happens next: true means continue, false means stop and throw an UnmarshalException. So to collect all errors, our handler records each event and returns true.

Java
record XmlError(int line, int column, String message) {}
Unmarshaller u = CTX.createUnmarshaller();
u.setSchema(ORDER_SCHEMA);
List<XmlError> errors = new ArrayList<>();
u.setEventHandler(event -> {
ValidationEventLocator loc = event.getLocator();
errors.add(new XmlError(loc.getLineNumber(), loc.getColumnNumber(), event.getMessage()));
return event.getSeverity() != ValidationEvent.FATAL_ERROR; // continue unless parsing is impossible
});
Order o = (Order) u.unmarshal(SafeXml.xmlInputFactory().createXMLStreamReader(new StringReader(xml)));
errors.forEach(System.out::println);
// XmlError[line=4, column=29, message=cvc-minInclusive-valid: Value '-3' is not facet-valid ... '1' ...]
// XmlError[line=5, column=15, message=cvc-complex-type.2.4.a: Invalid content was found starting with element '{"urn:acme:order":colour}' ...]
// XmlError[line=6, column=9, message=cvc-complex-type.2.4.b: The content of element 'order' is not complete ...]
if (!errors.isEmpty()) throw new InvalidOrderException(errors); // report all three at once
Step throughUnmarshalling with validation
  1. Read the next part of the document
  2. Does it match the schema?
    YesMap it into the objectNoReport a ValidationEvent
  3. Handler returns true?
    YesRecord the error and continueNoStop with UnmarshalException
  4. End of document
  5. Any errors recorded?
    YesReject with the full listNoUse the object

5 steps in order. Play them, or step through them one at a time.

Notice the severity check. Schema violations are reported as errors, and continuing after them is fine. A fatal error means the document is not even well-formed XML, for example a missing end tag, and the parser cannot continue whatever we return. JAXB also ships a ready-made handler, jakarta.xml.bind.util.ValidationEventCollector, which stores every event and continues; it is a good choice when we do not need to convert the events ourselves.

The object returned after errors is only partly trustworthy, so we never use it when the list is not empty. Its purpose is to let validation run to the end and gather the complete list.

4Hardening the Document Parsing Too

The schema factory settings protect schema compilation. The incoming document is a separate parse, and it is the one an attacker controls. If we unmarshal from a plain Reader or InputStream, the runtime creates its own parser, and its handling of DTDs depends on the runtime and version. That is why the example unmarshals from an XMLStreamReader created by our hardened factory, with DTDs and external entities disabled. That blocks XXE, the XML external entity attack that reads local files or calls internal URLs, and entity expansion attacks, whatever the JAXB runtime's defaults are.

5Packaging It as a Reusable Reader

Putting the pieces together, a small component owns the shared JAXBContext and Schema, which are both thread-safe, and creates a fresh Unmarshaller and error list per call, since those are not thread-safe. The result is either a valid Order or an exception carrying every error with its line and column, which the API can return to the partner in one response.

Java
@Component
class OrderReader {
private static final JAXBContext CTX = JaxbContexts.of(Order.class); // shared, thread-safe
private static final Schema SCHEMA = compile("/xsd/order.xsd"); // shared, thread-safe
Order read(InputStream in) throws Exception {
Unmarshaller u = CTX.createUnmarshaller(); // per call, not thread-safe
ValidationEventCollector collector = new ValidationEventCollector();
u.setSchema(SCHEMA);
u.setEventHandler(collector);
Object result = u.unmarshal(SafeXml.xmlInputFactory().createXMLStreamReader(in));
if (collector.hasEvents()) throw new InvalidOrderException(collector.getEvents());
return (Order) result;
}
}

The same Schema can be set on a Marshaller, so our own outgoing documents are checked against the partner's contract in tests or even in production, which catches mapping mistakes before the partner does.

6Follow-up questions

Is a Validator from schema.newValidator() thread-safe?

No. The Schema is thread-safe and can be shared, but Validator and ValidatorHandler objects created from it are not; create them per use, just like unmarshallers. When validating through JAXB with setSchema(), JAXB creates what it needs internally.

Does validation slow unmarshalling down much?

It adds some cost, typically a modest fraction of parsing time, because the validator checks each event as it streams by. For partner input, the safety is worth it. For trusted internal documents in a hot path, we might validate only in tests and at the boundary where data enters.

Can I limit how many errors are collected?

Yes. In our own handler, return false once the list reaches a limit such as 100. A badly broken file can otherwise produce thousands of events that are not useful to anyone and take memory.

7Conclusion

In this answer, we saw that JAXB without a schema silently accepts invalid documents. We compiled order.xsd once with SchemaFactory, keeping the thread-safe Schema in a constant, attached it with setSchema(), and collected every violation with a ValidationEventHandler that records each event and returns true, or with ValidationEventCollector. We hardened schema compilation with ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_SCHEMA set to empty, parsed the document itself through a hardened XMLStreamReader, and packaged everything as a reader that reports all errors at once.

What to say in the interviewAbout 80 seconds aloud

Open with

Without a schema, JAXB is lenient: it ignores unknown elements, leaves missing ones null and accepts bad values, so invalid data can pass silently. I would compile the XSD once with SchemaFactory.newInstance of the W3C XML Schema namespace and newSchema, passing a URL so relative includes resolve, and keep the Schema in a static final field, because compiling is expensive and the Schema is thread-safe.

Then, if they want more

Before compiling, I set ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_SCHEMA to an empty string on the factory, or allow only local protocols if the schema includes other files, never http.

For each document I create a new Unmarshaller, call setSchema, and set a ValidationEventHandler that adds each event, with its line, column and message, to a list and returns true, which means continue; returning false would stop at the first error. JAXB's ValidationEventCollector does the same. Fatal errors, meaning XML that is not well-formed, stop parsing regardless.

After unmarshalling, if the list is not empty I reject the document with all the errors, and never use the partial object. I also unmarshal from an XMLStreamReader built by a hardened factory with DTDs and external entities disabled, because the document itself is attacker-controlled.

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 "Validate incoming XML against an order.xsd while unmarshalling with JAXB, and collect...": https://scrivio-interview-library.netlify.app/java/jaxb/5f0840fcd0/