The Java runtime library supports validation. Last time I checked this was the Apache Xerces parser under the covers. You should probably use a javax.xml.validation.Validator.

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import java.net.URL;
import org.xml.sax.SAXException;
//import java.io.File; // if you use File
import java.io.IOException;
...
URL schemaFile = new URL("http://host:port/filename.xsd");
// webapp example xsd: 
// URL schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
// local file example:
// File schemaFile = new File("/location/to/localfile.xsd"); // etc.
Source xmlFile = new StreamSource(new File("web.xml"));
SchemaFactory schemaFactory = SchemaFactory
    .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
  Schema schema = schemaFactory.newSchema(schemaFile);
  Validator validator = schema.newValidator();
  validator.validate(xmlFile);
  System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
  System.out.println(xmlFile.getSystemId() + " is NOT valid reason:" + e);
} catch (IOException e) {}

The schema factory constant is the string http://www.w3.org/2001/XMLSchema which defines XSDs. The above code validates a WAR deployment descriptor against the URL http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd but you could just as easily validate against a local file.

You should not use the DOMParser to validate a document (unless your goal is to create a document object model anyway). This will start creating DOM objects as it parses the document - wasteful if you aren't going to use them.

Answer from McDowell on Stack Overflow
🌐
Baeldung
baeldung.com › home › xml › validate an xml file against an xsd file
Validate an XML File Against an XSD File | Baeldung
October 8, 2025 - The javax.xml.validation package defines an API for the validation of XML documents.
🌐
W3Schools
w3schools.com › xml › xml_validator.asp
XML Validator
Use our XML validator to syntax-check your XML.
🌐
Liquid Technologies
liquid-technologies.com › online-xml-validator
Free Online XML Validator (Well formed)
Java · Visual Basic 6 · Visual Basic .Net · XML Formatter · XML Validator · XML Validator (XSD) XML Validator (RelaxNG) XML Validator (Schematron) XML to XSD · XSD to XML · JSON Formatter · JSON Validator · JSON Validator (JSON Schema) JSON to JSON Schema ·
Top answer
1 of 13
353

The Java runtime library supports validation. Last time I checked this was the Apache Xerces parser under the covers. You should probably use a javax.xml.validation.Validator.

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import java.net.URL;
import org.xml.sax.SAXException;
//import java.io.File; // if you use File
import java.io.IOException;
...
URL schemaFile = new URL("http://host:port/filename.xsd");
// webapp example xsd: 
// URL schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
// local file example:
// File schemaFile = new File("/location/to/localfile.xsd"); // etc.
Source xmlFile = new StreamSource(new File("web.xml"));
SchemaFactory schemaFactory = SchemaFactory
    .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
  Schema schema = schemaFactory.newSchema(schemaFile);
  Validator validator = schema.newValidator();
  validator.validate(xmlFile);
  System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
  System.out.println(xmlFile.getSystemId() + " is NOT valid reason:" + e);
} catch (IOException e) {}

The schema factory constant is the string http://www.w3.org/2001/XMLSchema which defines XSDs. The above code validates a WAR deployment descriptor against the URL http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd but you could just as easily validate against a local file.

You should not use the DOMParser to validate a document (unless your goal is to create a document object model anyway). This will start creating DOM objects as it parses the document - wasteful if you aren't going to use them.

2 of 13
25

Here's how to do it using Xerces2. A tutorial for this, here (req. signup).

Original attribution: blatantly copied from here:

import org.apache.xerces.parsers.DOMParser;
import java.io.File;
import org.w3c.dom.Document;

public class SchemaTest {
  public static void main (String args[]) {
      File docFile = new File("memory.xml");
      try {
        DOMParser parser = new DOMParser();
        parser.setFeature("http://xml.org/sax/features/validation", true);
        parser.setProperty(
             "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", 
             "memory.xsd");
        ErrorChecker errors = new ErrorChecker();
        parser.setErrorHandler(errors);
        parser.parse("memory.xml");
     } catch (Exception e) {
        System.out.print("Problem parsing the file.");
     }
  }
}
🌐
FreeFormatter
freeformatter.com › xml-validator-xsd.html
Free Online XML Validator Against XSD Schema - FreeFormatter.com
This free online XML validator lets you validate your XML files against an XSD (XML Schema)
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-validate-xml-against-xsd-in-java
How to validate XML against XSD in Java | DigitalOcean
August 3, 2022 - javax.xml.validation.Validator class is used in this program to validate xml against xsd in java.
Top answer
1 of 3
51

You can check if an XML document is well-formed using the following code:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);

DocumentBuilder builder = factory.newDocumentBuilder();

builder.setErrorHandler(new SimpleErrorHandler());    
// the "parse" method also validates XML, will throw an exception if misformatted
Document document = builder.parse(new InputSource("document.xml"));

The SimpleErrorHandler class referred to in the above code is as follows:

public class SimpleErrorHandler implements ErrorHandler {
    public void warning(SAXParseException e) throws SAXException {
        System.out.println(e.getMessage());
    }

    public void error(SAXParseException e) throws SAXException {
        System.out.println(e.getMessage());
    }

    public void fatalError(SAXParseException e) throws SAXException {
        System.out.println(e.getMessage());
    }
}

This came from this website, which provides various methods for validating XML with Java. Note also that this method loads an entire DOM tree into memory, see comments for alternatives if you want to save on RAM.

2 of 3
5

What you are asking is how to verify that a piece of content is well-formed XML document. This is easily done by simply letting an XML parser (try to) parse content in question -- if there are issues, parser will report an error by throwing exception. There really isn't anything more to that; so all you need is to figure out how to parse an XML document.

About the only thing to beware is that some libs that claim to be XML parsers are not really proper parsers, in that they actually might not verify things that XML parser must do (as per XML specification) -- in Java, Javolution is an example of something that does little to no checking; VTD-XML and XPP3 do some verification (but not all required checks). And at the other end of spectrum, Xerces and Woodstox check everything that specification mandates. Xerces is bundled with JDK; and most web service frameworks bundle Woodstox in addition.

Since the accepted answer already shows how to parse content into a DOM document (which starts with parsing), that might be enough. The only caveat is that this requires that you have 3-5x as much memory available as raw size of the input document. To get around this limitation you could use a streaming parser, such as Woodstox (which implements standard Stax API). If so, you would create an XMLStreamReader, and just call reader.next() as long as reader.hasNext() returns true.

Find elsewhere
🌐
Utilities and Tools
utilities-online.info › xsdvalidation
W3C XML Schema (XSD) Validation online
Identifying and resolving errors in a project is time-consuming and frustrating sometimes. Fortunately, the features provided by this XML XSD validator make it quicker and easier to recognize mistakes. This XSD validator tool provides the latest version of the Java API for XML Processing to verify files against XML Schemas.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › javax › xml › validation › package-summary.html
javax.xml.validation (Java Platform SE 8 )
October 20, 2025 - Java™ Platform Standard Ed. 8 ... This package provides an API for validation of XML documents.
🌐
Easycodeforall
easycodeforall.com › XMLValidation.jsp
Online Tool To Validate XML against a XSD (XML Schema). online schema validator - www.easycodeforall.com
Generate JavaDoc Comments · Replace ... interface agreement document(XSD) is required. . This XSD needs to be validated with an XML. This online tool (XSD validator) is used to validate XSD....
🌐
Cmu
pslcdatashop.web.cmu.edu › about › xmlvalidator.html
DataShop > Downloads > XML Validator Tool
It will also perform custom validation pertinent to DataShop processing expectations. DataShop can process multiple XML files for inclusion in a single dataset. When receiving XML data, we prefer many smaller files as opposed to a few large files. ... Note: Java must be installed and available from the command line.
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.xml › javax › xml › validation › package-summary.html
javax.xml.validation (Java SE 11 & JDK 11 )
October 20, 2025 - Provides an API for validation of XML documents. Validation is the process of verifying that an XML document is an instance of a specified XML schema.
🌐
Liquid Technologies
liquid-technologies.com › online-xsd-validator
Free Online XML Validator (XSD)
Java · Visual Basic 6 · Visual Basic .Net · XML Formatter · XML Validator · XML Validator (XSD) XML Validator (RelaxNG) XML Validator (Schematron) XML to XSD · XSD to XML · JSON Formatter · JSON Validator · JSON Validator (JSON Schema) JSON to JSON Schema ·
🌐
Code Beautify
codebeautify.org › xmlvalidator
XML Validator Tool to validate XML online: XML Lint
XML validator will check for both well-formedness and validity. It will also give you helpful error messages so you can fix any issues in your XML. The XML syntax rules are less stringent compared to the formal rules of well-known languages ...
🌐
JSON Formatter
jsonformatter.org › xml-validator
Best XML Validator Online
XML Validator Online helps to Edit, View, Analyse XML data along with formatting XML data.
🌐
Frankel
blog.frankel.ch › xml-schema-validation-1-1
XML Schema Validation 1.1 in Java
November 9, 2025 - An XML Schema Processor. This supports both XSD 1.0 and XSD 1.1. This can be used on its own to validate a schema for correctness, or to validate a source document against the definitions in a schema.
🌐
HowToDoInJava
howtodoinjava.com › home › jaxb › jaxb schema validation
JAXB Schema Validation - Validate XML against XSD
February 12, 2024 - Learn to validate XML against schema (xsd) and then unmarshalling XML to Java object in this JAXB schema validation example and to check validation errors.
🌐
Taylorandfrancis
jats.taylorandfrancis.com › tfjats › validation
TF JATS Validation Tool
Trusted code signing certificate added for compatibility with RIA changes in Java 7u51. When an article XML or issue XML file is provided as input validation is now run on the containing folder so that all normal validation checks are done (instead of only XML validation).