Validating XML with XML Schema: Types, Sequences and a Practical Example
Validate XML against an XML Schema (XSD) in Java: simple and complex types, restrictions with enumerations and patterns, sequence, choice, groups, occurrence limits, attribute defaults, SchemaFactory, Validator and setSchema, plus a config file that builds objects.
kvi5hnuCode Sprout team member10 min readOn this page
DTDs (article 41) describe structure, but they know almost nothing about values. To a DTD, <size>36</size> and <size>large</size> are equally valid. XML Schema (W3C XML Schema Definition Language, XSD) closes that gap. It has data types such as integers, dates and booleans, it lets you restrict them further, and schema files are themselves XML documents, so XML tools can process them. The price is verbosity: schemas are long, and the full language is large. This article covers the parts you need for typical data formats.
The JDK validates against XML Schema 1.0. Version 1.1 (2012), which adds assertions and conditional types, needs a third-party library.
Pointing a document to its schema
A document can name its schema with attributes on the root element:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="config.xsd">
...
</config>
xsi is a namespace prefix (article 44 explains namespaces). For documents that use a target namespace, the attribute is xsi:schemaLocation with pairs of namespace and location. In practice, an application usually knows which schema it expects and applies it itself, which is also safer than trusting a location from the document.
Simple and complex types
Every element and attribute in a schema has a type:
- A simple type is text with constraints. Attributes always have simple types. An element with a simple type has neither attributes nor child elements.
- A complex type is anything else: an element with child elements, attributes, or both.
XSD has about 45 built-in simple types. The most useful include:
| Type | Values |
|---|---|
xsd:string, xsd:token | any text; token also collapses whitespace |
xsd:int, xsd:long, xsd:integer, xsd:decimal, xsd:double | numbers (integer and decimal are unbounded) |
xsd:positiveInteger, xsd:nonNegativeInteger | integer subranges |
xsd:boolean | true, false, 1, 0 |
xsd:date, xsd:dateTime, xsd:time, xsd:duration | ISO 8601 values such as 2026-11-14 and PT90S |
xsd:anyURI, xsd:NCName, xsd:ID, xsd:IDREF | URIs, XML names, IDs and references to them |
The prefix is just a convention. Some authors write xs: instead of xsd:. What matters is that it's bound to the namespace http://www.w3.org/2001/XMLSchema.
Restricting a simple type
New simple types are derived by restriction, using constraints called facets:
<xsd:simpleType name="StyleType">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="PLAIN"/>
<xsd:enumeration value="BOLD"/>
<xsd:enumeration value="ITALIC"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="Percent">
<xsd:restriction base="xsd:int">
<xsd:minInclusive value="0"/>
<xsd:maxInclusive value="100"/>
</xsd:restriction>
</xsd:simpleType>
Other facets include pattern (a regular expression, in a dialect close to Java's; the whole value must match), minLength, maxLength, length, totalDigits and fractionDigits. Simple types can also be built as xsd:list (whitespace-separated values) or xsd:union.
Declaring elements
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="size" type="xsd:int"/>
<xsd:element name="style" type="StyleType"/>
With these declarations, <size>10</size> and <style>PLAIN</style> are valid. <size>default</size> and <style>SLANTED</style> are rejected.
Complex types
A complex type arranges child elements with compositors:
| XSD | DTD equivalent |
|---|---|
<xsd:sequence> | (a, b, c): in this order |
<xsd:choice> | (a | b | c): one of them |
<xsd:all> | each at most once, in any order (no DTD equivalent) |
minOccurs="0" maxOccurs="unbounded" | * (the defaults are 1 and 1, so minOccurs="0" alone is ?) |
<xsd:complexType name="FontType">
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="size" type="xsd:int"/>
<xsd:element name="style" type="StyleType" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
Type definitions can be named and reused, as above, or anonymous, nested directly inside the element that uses them. An element can also refer to a global element declaration with ref="name" instead of name and type. Parts of content models that recur in several places can be packaged as named xsd:groups and included with <xsd:group ref="..."/>. The example below uses this technique heavily.
Attributes
Attributes are declared after the content model of a complex type:
<xsd:element name="size">
<xsd:complexType>
<xsd:simpleContent>
<xsd:extension base="xsd:int">
<xsd:attribute name="unit" type="xsd:string" use="optional" default="cm"/>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
simpleContent with an extension is the idiom for "text of some simple type, plus attributes". The use attribute is optional (the default), required or prohibited. default supplies a value when the attribute is absent, and fixed forces one. The equivalent DTD declaration would be <!ATTLIST size unit CDATA "cm">, though the DTD couldn't check that the content is an integer.
The whole schema is wrapped in a root element:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
...
</xsd:schema>
Beyond ID/IDREF, schemas also have xsd:unique, xsd:key and xsd:keyref, which define uniqueness and references with XPath expressions over any element or attribute values.
Validating in Java
The javax.xml.validation package (Java 5) compiles a schema once and then applies it in several ways:
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(Path.of("config.xsd").toFile());
A Schema is immutable and thread-safe, so compile it once and share it.
Validate while parsing. Attach the schema to the parser factory. Don't call setValidating(true), which would request DTD validation in addition:
var factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setSchema(schema);
factory.setIgnoringElementContentWhitespace(true);
The validated tree contains attribute defaults from the schema, and, as with DTDs, whitespace in element-only content is dropped.
Validate on its own. A Validator checks a source without building anything you need to keep:
Validator validator = schema.newValidator();
validator.setErrorHandler(handler);
validator.validate(new StreamSource(file)); // also DOMSource, SAXSource, StAXSource
A Validator isn't thread-safe. Make one per thread, or per use.
The same error-handling rule as for DTDs applies. Validity errors go to ErrorHandler.error and don't stop processing. Without a handler, the Validator throws on the first error. Error messages begin with codes such as cvc-complex-type.2.4.a that refer to sections of the XSD specification ("cvc" means "validation rule").
Older code uses a property instead of setSchema, letting the parser load the schema named in the document through xsi:noNamespaceSchemaLocation:
factory.setNamespaceAware(true);
factory.setValidating(true);
factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
XMLConstants.W3C_XML_SCHEMA_NS_URI);
It still works, but the Schema API is clearer, faster (the schema is compiled once), and doesn't depend on what the document says about itself.
A practical example: objects from a configuration file
This example shows how much code validation saves. Suppose a program reads a configuration that describes arbitrary Java objects, not just strings. An object is built either with a constructor or with a static factory method, and arguments are primitive values, strings or further objects:
<config>
<entry id="release">
<factory class="java.time.LocalDate" method="of">
<int>2026</int>
<int>9</int>
<value type="int">15</value>
</factory>
</entry>
<entry id="price">
<construct class="java.math.BigDecimal">
<string>19.99</string>
</construct>
</entry>
<entry id="calendar">
<factory class="java.util.Calendar"/>
</entry>
</config>
There are two ways to write a primitive: <int>15</int>, or <value type="int">15</value>. When method is missing, it defaults to getInstance.
The schema in the program enforces all of it:
idis anxsd:ID, so it's required, must be a valid XML name, and must be unique.int,longandbooleancontents must parse as those types.- The
typeattribute ofvalueis an enumeration. classmust match a pattern for a qualified Java name.- An entry holds exactly one object.
constructandfactoryhold any number of objects. These are expressed with two reusable groups,ObjectandPrimitive. methodhas the defaultgetInstance, which the parser inserts into the tree.
As a result, the code that turns the tree into objects has no error checking at all. It casts every child node to Element without testing it, calls Integer.parseInt without catching exceptions, and reads the method attribute knowing that it's always present. Only problems the schema can't detect remain, such as a class that doesn't exist or has no matching constructor. These are reported as reflection exceptions.
The program also runs a series of broken documents through a Validator to show the messages.
import java.io.*;
import java.lang.reflect.*;
import java.nio.file.*;
import java.util.*;
import javax.xml.XMLConstants;
import javax.xml.parsers.*;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class Solution {
static final String XSD = """
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="config">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="entry" type="EntryType" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="EntryType">
<xsd:group ref="Object"/>
<xsd:attribute name="id" type="xsd:ID" use="required"/>
</xsd:complexType>
<xsd:group name="Object">
<xsd:choice>
<xsd:element name="construct" type="ConstructType"/>
<xsd:element name="factory" type="FactoryType"/>
<xsd:group ref="Primitive"/>
</xsd:choice>
</xsd:group>
<xsd:group name="Primitive">
<xsd:choice>
<xsd:element name="int" type="xsd:int"/>
<xsd:element name="long" type="xsd:long"/>
<xsd:element name="boolean" type="xsd:boolean"/>
<xsd:element name="string" type="xsd:string"/>
<xsd:element name="value" type="ValueType"/>
</xsd:choice>
</xsd:group>
<xsd:complexType name="ConstructType">
<xsd:group ref="Object" minOccurs="0" maxOccurs="unbounded"/>
<xsd:attribute name="class" type="ClassName" use="required"/>
</xsd:complexType>
<xsd:complexType name="FactoryType">
<xsd:group ref="Object" minOccurs="0" maxOccurs="unbounded"/>
<xsd:attribute name="class" type="ClassName" use="required"/>
<xsd:attribute name="method" type="xsd:NCName" default="getInstance"/>
</xsd:complexType>
<xsd:complexType name="ValueType">
<xsd:simpleContent>
<xsd:extension base="xsd:string">
<xsd:attribute name="type" use="required">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="int"/>
<xsd:enumeration value="long"/>
<xsd:enumeration value="boolean"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
<xsd:simpleType name="ClassName">
<xsd:restriction base="xsd:string">
<xsd:pattern value="[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)*"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
""";
static final String CONFIG = """
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="config.xsd">
<entry id="release">
<factory class="java.time.LocalDate" method="of">
<int>2026</int>
<int>9</int>
<value type="int">15</value>
</factory>
</entry>
<entry id="timeout">
<factory class="java.time.Duration" method="ofSeconds">
<long>90</long>
</factory>
</entry>
<entry id="price">
<construct class="java.math.BigDecimal">
<string>19.99</string>
</construct>
</entry>
<entry id="greeting">
<construct class="java.lang.StringBuilder">
<string>Hello</string>
</construct>
</entry>
<entry id="verbose"><boolean>true</boolean></entry>
<entry id="calendar">
<factory class="java.util.Calendar"/>
</entry>
</config>
""";
static class Collector implements ErrorHandler {
final List<String> messages = new ArrayList<>();
public void warning(SAXParseException e) { messages.add("warning: " + e.getMessage()); }
public void error(SAXParseException e) { messages.add("line " + e.getLineNumber() + ": " + e.getMessage()); }
public void fatalError(SAXParseException e) throws SAXException { throw e; }
}
// ---------- turning a validated tree into objects ----------
record Arg(Class<?> type, Object value) { }
static Arg parseObject(Element e) throws ReflectiveOperationException {
return switch (e.getTagName()) {
case "int", "long", "boolean", "string" -> primitive(e.getTagName(), e.getTextContent());
case "value" -> primitive(e.getAttribute("type"), e.getTextContent());
case "construct" -> {
Class<?> cl = Class.forName(e.getAttribute("class"));
List<Arg> args = parseArgs(e);
Constructor<?> c = cl.getConstructor(types(args));
yield new Arg(cl, c.newInstance(values(args)));
}
case "factory" -> {
Class<?> cl = Class.forName(e.getAttribute("class"));
List<Arg> args = parseArgs(e);
Method m = cl.getMethod(e.getAttribute("method"), types(args)); // default supplied by the schema
yield new Arg(cl, m.invoke(null, values(args)));
}
default -> throw new IllegalStateException("schema should have prevented " + e.getTagName());
};
}
static Arg primitive(String type, String text) {
return switch (type) {
case "int" -> new Arg(int.class, Integer.parseInt(text));
case "long" -> new Arg(long.class, Long.parseLong(text));
case "boolean" -> new Arg(boolean.class, Boolean.parseBoolean(text));
default -> new Arg(String.class, text);
};
}
static List<Arg> parseArgs(Element parent) throws ReflectiveOperationException {
var args = new ArrayList<Arg>();
for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling())
args.add(parseObject((Element) n)); // safe: only elements remain after validation
return args;
}
static Class<?>[] types(List<Arg> args) { return args.stream().map(Arg::type).toArray(Class<?>[]::new); }
static Object[] values(List<Arg> args) { return args.stream().map(Arg::value).toArray(); }
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("xsd");
Path xsd = dir.resolve("config.xsd");
Path xml = dir.resolve("config.xml");
try {
Files.writeString(xsd, XSD);
Files.writeString(xml, CONFIG);
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(xsd.toFile());
System.out.println("--- parse with a schema, then build objects ---");
var factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setSchema(schema);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = factory.newDocumentBuilder();
var errors = new Collector();
builder.setErrorHandler(errors);
Document doc = builder.parse(xml.toFile());
System.out.println("errors: " + errors.messages);
var config = new LinkedHashMap<String, Object>();
for (Node n = doc.getDocumentElement().getFirstChild(); n != null; n = n.getNextSibling()) {
var entry = (Element) n;
Object value = parseObject((Element) entry.getFirstChild()).value();
config.put(entry.getAttribute("id"), value);
}
config.forEach((id, value) -> System.out.printf("%-9s %-22s %s%n", id, value.getClass().getName(),
value instanceof Calendar ? "(a Calendar)" : value));
System.out.println("--- the Validator API ---");
Validator validator = schema.newValidator();
String[] samples = {
"<config/>",
"<config><entry id='a'><int>12</int></entry><entry id='a'><int>13</int></entry></config>",
"<config><entry id='b'><int>twelve</int></entry></config>",
"<config><entry id='c'><value type='double'>1.5</value></entry></config>",
"<config><entry id='d'><construct class='java..Bad'/></entry></config>",
"<config><entry id='e'><int>1</int><int>2</int></entry></config>",
"<config><entry><boolean>maybe</boolean></entry></config>",
"<config><entry id='3x'><string/></entry></config>",
};
for (String sample : samples) {
var collector = new Collector();
validator.setErrorHandler(collector);
validator.validate(new StreamSource(new StringReader(sample)));
System.out.println(sample);
System.out.println(" " + (collector.messages.isEmpty() ? "valid" : String.join("\n ", collector.messages)));
}
System.out.println("--- the older property-based switch ---");
var legacy = DocumentBuilderFactory.newInstance();
legacy.setNamespaceAware(true);
legacy.setValidating(true);
legacy.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
XMLConstants.W3C_XML_SCHEMA_NS_URI);
DocumentBuilder lb = legacy.newDocumentBuilder();
var le = new Collector();
lb.setErrorHandler(le);
lb.parse(xml.toFile()); // finds config.xsd through xsi:noNamespaceSchemaLocation
System.out.println("validated via xsi:noNamespaceSchemaLocation, errors: " + le.messages);
} finally {
Files.delete(xsd);
Files.delete(xml);
Files.delete(dir);
}
}
}
--- parse with a schema, then build objects ---
errors: []
release java.time.LocalDate 2026-09-15
timeout java.time.Duration PT1M30S
price java.math.BigDecimal 19.99
greeting java.lang.StringBuilder Hello
verbose java.lang.Boolean true
calendar java.util.GregorianCalendar (a Calendar)
--- the Validator API ---
<config/>
valid
<config><entry id='a'><int>12</int></entry><entry id='a'><int>13</int></entry></config>
line 1: cvc-id.2: There are multiple occurrences of ID value 'a'.
line 1: cvc-attribute.3: The value 'a' of attribute 'id' on element 'entry' is not valid with respect to its type, 'ID'.
<config><entry id='b'><int>twelve</int></entry></config>
line 1: cvc-datatype-valid.1.2.1: 'twelve' is not a valid value for 'integer'.
line 1: cvc-type.3.1.3: The value 'twelve' of element 'int' is not valid.
<config><entry id='c'><value type='double'>1.5</value></entry></config>
line 1: cvc-enumeration-valid: Value 'double' is not facet-valid with respect to enumeration '[int, long, boolean]'. It must be a value from the enumeration.
line 1: cvc-attribute.3: The value 'double' of attribute 'type' on element 'value' is not valid with respect to its type, '#AnonType_typeValueType'.
<config><entry id='d'><construct class='java..Bad'/></entry></config>
line 1: cvc-pattern-valid: Value 'java..Bad' is not facet-valid with respect to pattern '[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*' for type 'ClassName'.
line 1: cvc-attribute.3: The value 'java..Bad' of attribute 'class' on element 'construct' is not valid with respect to its type, 'ClassName'.
<config><entry id='e'><int>1</int><int>2</int></entry></config>
line 1: cvc-complex-type.2.4.d: Invalid content was found starting with element 'int'. No child element is expected at this point.
<config><entry><boolean>maybe</boolean></entry></config>
line 1: cvc-complex-type.4: Attribute 'id' must appear on element 'entry'.
line 1: cvc-datatype-valid.1.2.1: 'maybe' is not a valid value for 'boolean'.
line 1: cvc-type.3.1.3: The value 'maybe' of element 'boolean' is not valid.
<config><entry id='3x'><string/></entry></config>
line 1: cvc-datatype-valid.1.2.1: '3x' is not a valid value for 'NCName'.
line 1: cvc-attribute.3: The value '3x' of attribute 'id' on element 'entry' is not valid with respect to its type, 'ID'.
--- the older property-based switch ---
validated via xsi:noNamespaceSchemaLocation, errors: []
Compare the effort: the schema is about 70 lines of declarations, and in exchange the reading code shrinks to a switch over tag names. The same pattern underlies frameworks that configure applications from XML, such as older Spring versions.
Common questions
How do I collect all validation errors instead of stopping at the first?
Install an ErrorHandler whose error method records the SAXParseException (with getLineNumber() and getMessage()) and returns normally. Processing then continues, and you report the list at the end. Throw only from fatalError, which is for well-formedness errors after which parsing cannot continue anyway.
Can I generate a schema, or Java classes, instead of writing them by hand?
Tools exist outside the JDK. Jakarta XML Binding (xjc) generates classes from a schema, and schemagen does the reverse. IDEs and tools such as trang can infer a starting schema from sample documents. The xjc and schemagen tools were removed from the JDK with Java EE in Java 11 (JEP 320), so they now come with the Jakarta implementation.
How do I validate a document that uses a target namespace?
Give the schema targetNamespace="..." and usually elementFormDefault="qualified", put the document's elements in that namespace, and parse with a namespace-aware factory. Without elementFormDefault="qualified", only global elements are in the namespace, a classic source of "cvc-complex-type.2.4.a: Invalid content was found" errors.
Can a schema be split across several files?
Yes. xsd:include pulls in a file with the same target namespace, and xsd:import brings in components from another namespace. SchemaFactory.newSchema(Source[]) also accepts several sources. Use an LSResourceResolver on the factory to load included files from the class path instead of the network.
What does "cvc-elt.1.a: Cannot find the declaration of element" mean? The root element of the document doesn't match any global element in the schema. Usually the namespace is wrong: the document element is in a namespace and the schema has none, or the other way around, or the parser isn't namespace-aware.
Is validation slow? Should I validate in production?
It costs roughly as much as parsing again, which is acceptable for most inputs. Validate data from outside your trust boundary. Compile the Schema once, because compiling is the expensive part. For internally generated data in a hot path, validating in tests may be enough.
API reference
| API | Purpose |
|---|---|
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) | factory for XSD schemas |
SchemaFactory.newSchema(File / URL / Source...) | compile a schema (thread-safe result) |
Schema.newValidator() | validator for one thread at a time |
Validator.validate(Source), validate(Source, Result) | check a document, optionally producing the augmented result |
Validator.setErrorHandler(handler) | collect or act on validation errors |
DocumentBuilderFactory.setSchema(schema) | validate while building a DOM |
SAXParserFactory.setSchema(schema) | validate while SAX parsing |
setNamespaceAware(true) | required for schema validation |
StreamSource, DOMSource, SAXSource, StAXSource | inputs for validators and transformers |
XMLConstants.ACCESS_EXTERNAL_SCHEMA | restrict protocols for imported schemas |
Summary
- XML Schema adds data types to structure checking. Simple types hold text, and complex types hold children and attributes.
- Derive simple types by restriction with facets such as
enumeration,pattern,minInclusiveandmaxLength. - Build complex types with
sequence,choiceandall, set repetition withminOccurs/maxOccurs, and reuse parts with named types and groups. - Attributes can be
requiredand can havedefaultorfixedvalues.simpleContentcombines typed text with attributes. - Compile a
Schemaonce withSchemaFactory, then validate withDocumentBuilderFactory.setSchemawhile parsing, or with aValidator. - After validation, reading code can skip almost all checks. That's the main payoff.
Practice Questions
Write a simple type for a US ZIP code: five digits, optionally followed by a hyphen and four digits.
<xsd:simpleType name="ZipCode">
<xsd:restriction base="xsd:string">
<xsd:pattern value="\d{5}(-\d{4})?"/>
</xsd:restriction>
</xsd:simpleType>
Schema patterns are implicitly anchored, so the whole value must match.
How do you express the DTD content model (title, author+, isbn?) in XML Schema?
<xsd:sequence>
<xsd:element name="title" type="xsd:string"/>
<xsd:element name="author" type="xsd:string" maxOccurs="unbounded"/>
<xsd:element name="isbn" type="xsd:string" minOccurs="0"/>
</xsd:sequence>
minOccurs and maxOccurs default to 1.
Why does the configuration reader call getAttribute("method") without checking for an empty string?
The schema declares method with default="getInstance", and a parser that validates against the schema inserts the default value into the tree when the attribute is missing. So the attribute is always present after validation.
What's the difference between factory.setSchema(schema) and factory.setValidating(true)?
setSchema validates against a compiled XML Schema that your program supplies. setValidating(true) turns on DTD validation, using the DTD named in the document. (With the legacy schemaLanguage property, it validates against the schema the document names instead.) Using both at once validates against the DTD and the schema, which is rarely intended.
Can a Schema and a Validator be shared among threads?
A Schema is immutable and thread-safe, so it should be compiled once and shared. A Validator (like a DocumentBuilder) holds state during validation and isn't thread-safe. Create one per thread or per validation, which is cheap compared to compiling the schema.
Previous: Validating XML with Document Type Definitions (DTDs)
Next: Querying XML with XPath: Expressions and the XPath API
Related reading
- Validating XML with Document Type Definitions (DTDs)
- Parsing XML with DOM: DocumentBuilder, Nodes and Secure Parsing
- Introducing XML: Document Structure, Elements and Attributes
- Java Regex Split, Replace and Flags: splitWithDelimiters, replaceAll and Pattern Flags
- Java Regex Matching: matches, find, Groups and Named Groups

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.