4

XML スキーマ仕様では、多くの組み込みデータ型が定義されていますhttp://www.w3.org/TR/xmlschema-2/#built-in-datatypes天気に関する質問に答えることができる Java ライブラリはありますか?値は特定のデータですタイプ。線に沿った何か。

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

更新: これの使用例は、XML のコンテキストではなく、XSD 型の 1 つに準拠したい文字列があり、それが準拠していることを確認する標準的な方法が必要な状況です。たとえば、文字列は、受信する JSON リクエストから抽出した値、または URL やその他の場所から抽出した値などである可能性があります。

4

2 に答える 2

2

以下は、JDK/JREで使用できる可能性のあるいくつかのクラスです。

javax.xml.datatype.XMLGregorianCalendar

javax.xml.datatype.XMLGregorianCalendar日付/時刻タイプについては、JavaSE5以降のJDK/JREの一部として含まれているものを使用できます。

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

javax.xml.bind.DatatypeConveter

悪い値に対してjavax.xml.bind.DatatypeConveterをスローすることもあります:IllegalArgumentException

DatatypeConverter.parseDate("2012-06-18");
于 2012-09-17T23:29:27.530 に答える
1

Here is a solution that uses the Xerces parser/validator. It uses .impl classes however. Those are not part of the public API and 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 like 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 yourself is to create methods for each of the data types. You should be able to find all the required classes in the org.apache.xerces.impl.dv.xs package.

Again, this is kind of abusing the Xerces library, as these classes are not part of the public API. So if you find another, cleaner solution, let us know.

于 2012-09-17T22:24:25.283 に答える