Java – Validate String against Xml Schema Datatype in Java


Is there a standard way to validate a string against any of the standard xml schema datatypes (see XML Schema Part 2: Datatypes Second Edition or more specifically Built-in-datatypes)?

I don't want to validate a complete XSD, I just wand to validate some user input against XML datatypes (e.g. against or Is there a way to do it using standard APIs? If not, are there other possibilitie instead of writing it from scratch?

The classes in the package javax.xml.validation seem to be targeted at validating complete schemas instead of specific datatypes.

Example of what I am trying to do:

String content = "abc";
String datatype = "";
boolean isValid = Validator.isValid(content, datatype); //return false

Best Solution

Not a standard API, but Xerces has an XML Scheam API that might be of interest. In Xerces you can also find data type validators that enables you to do this:

import org.apache.xerces.impl.dv.InvalidDatatypeValueException;
import org.apache.xerces.impl.dv.xs.YearDV;

public class Main {

public static void main(String[] args)  {
    try {
        new YearDV().getActualValue("Notayear", null);
    } catch (InvalidDatatypeValueException e) {

which would print

cvc-datatype-valid.1.2.1: 'Notayear' is not a valid value for 'gYear'.

Take it from there. Lots of code to read!

Related Question