Regular expression or library for checking built-in XSD types?

The XML Schema specification defines many built-in data types. Http://www.w3.org/TR/xmlschema-2/#built-in-datatypes is a Java library that can answer weather questions, aa value is a specific data type. Something along the lines.

if(XSDValidator.isXSDDate("2012-06-12") == false) { // return error } 

Update: The use case for this is not XML, but rather in situations where I have a string that I want to match one of the XSD types, and I want a standard way to check that it matches. For example, a string could be a value that I am retrieving from an incoming JSON request, or from a URL or any other place ... etc.

+4
source share
2 answers

Below are some classes available in the JDK / JRE that you could use:

javax.xml.datatype.XMLGregorianCalendar

For date / time types, you can use javax.xml.datatype.XMLGregorianCalendar , which is included as part of the JDK / JRE with Java SE 5.

 DatatypeFactory df = DatatypeFactory.newInstance(); XMLGregorianCalendar xgc = df.newXMLGregorianCalendar("2012-06-18"); return DatatypeConstants.DATE.equals(xgc.getXMLSchemaType()); 

javax.xml.bind.DatatypeConveter

There is also javax.xml.bind.DatatypeConveter which throws an IllegalArgumentException for bad values:

 DatatypeConverter.parseDate("2012-06-18"); 
+2
source

Here is a solution that uses the Xerces parser / validator. However, it does use .impl classes. They are not part of the public API and are subject to change. But if you stick to a certain version, you should be fine.

First, the dependency:

 <dependency> <groupId>xerces</groupId> <artifactId>xerces</artifactId> <version>2.4.0</version> </dependency> 

And here is a small program that works as you described:

 import org.apache.xerces.impl.dv.InvalidDatatypeValueException; import org.apache.xerces.impl.dv.xs.DateDV; public class XSDValidator { public static void main(final String[] args) { System.out.println(isXSDDate("2012-09-18")); System.out.println(isXSDDate("Hello World")); } private static boolean isXSDDate(final String string) { try { new DateDV().getActualValue(string); return true; } catch(final InvalidDatatypeValueException e) { return false; } } } 

Output:

 true false 

All you have to do is create methods for each of the data types. You should find all the required classes in the org.apache.xerces.impl.dv.xs package.

Again, this is a kind of abuse of the Xerces library, as these classes are not part of the public API. Therefore, if you find a different, cleaner solution, let us know.

+1
source

Source: https://habr.com/ru/post/1434642/


All Articles