Skip to main content

Search 412 pages — tools, formats, elements, namespaces, directory, comparisons, XPath, datatypes, glossary, parse errors, schema errors, use cases, guides, blog and product.

Languages guide

Validate XML in Java with JAXP

Use Java's built-in validation API safely, compile reusable Schema objects, collect SAX errors, and control external schema resolution.

9 min read · Updated 2026-08-21

The short answer

Create a SchemaFactory for W3C XML Schema, disable external DTD and schema access unless a controlled resolver is required, compile the XSD into a thread-safe Schema, and create a fresh Validator for each validation operation. Handle schema compilation SAXException separately from instance violations, and install an ErrorHandler when you need more than the first diagnostic.

Compile a controlled schema set

SchemaFactory is the compiler entry point and is neither thread-safe nor re-entrant. Configure it before compilation, resolve dependencies from approved local sources, then share the resulting immutable Schema rather than sharing the factory or a mutable Validator.

JAXP validation skeleton
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
factory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
factory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");

Schema schema = factory.newSchema(Path.of("contract.xsd").toFile());
Validator validator = schema.newValidator();
validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
validator.validate(new StreamSource(Path.of("payload.xml").toFile()));

Keep compilation and instance errors distinct

factory.newSchema fails when the grammar cannot be compiled. validator.validate fails when the instance cannot be read or does not satisfy that grammar. Report those phases separately; otherwise teams waste time editing a payload when an import URI or type declaration is broken.

  • Create a new Validator per operation or thread.
  • Use an ErrorHandler to collect warnings and errors deliberately.
  • Give StreamSource objects system IDs when relative imports are legitimate.
  • Never enable arbitrary external access just to make a missing import disappear.

Make production behavior testable

Run known-good, boundary, and known-bad documents through the same compiled Schema used by the service. Assert the diagnostic phase as well as the final pass or fail result.

If the application subsequently unmarshals XML, validate before binding and retain namespace-aware names. XSD validation does not make unsafe polymorphic binding, external resolution, or business authorization safe by itself.

Get started

Bring order to the XML your team can't afford to ignore.

Create a free account and get a private workspace to search, validate, diff, and monitor your XML feeds, sitemaps, schemas, and vendor integrations.