3
votes

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 http://www.w3.org/2001/XMLSchema#date or http://www.w3.org/2001/XMLSchema#boolean). 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 = "http://www.w3.org/2001/XMLSchema#long";
boolean isValid = Validator.isValid(content, datatype); //return false
2

2 Answers

1
votes

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);
        System.out.println("OK");
    } catch (InvalidDatatypeValueException e) {
        System.out.println(e.getMessage());
    }
}

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!

0
votes

you can do the following:

public boolean validate(String inputXml, String schemaLocation)throws SaxException, throws IOException {
// build the schema
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
File schemaFile = new File(schemaLocation);
Schema schema = factory.newSchema(schemaFile);
Validator validator = schema.newValidator();

// create a source from a string
Source source = new StreamSource(new StringReader(inputXml));

// check input
boolean isValid = true;
try {
validator.validate(source);
} catch (SaxException e) {
System.err.printlin("Not valid");
isValid = false;
}

return isValid;
}