2013-12-14 5 views
1

나는이 같은 방법이 있습니다JAXB 사용자 정의 유효성 검사기

private static <T> T readXML(final String file, final String schemaFile, final Class<T> clazz) { 
    try { 
     final JAXBContext context = JAXBContext.newInstance(clazz); 
     final Unmarshaller unmarshaller = context.createUnmarshaller(); 
     unmarshaller.setEventHandler(new EventHandler()); 
     final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
     final String directory = System.getProperty("schema.dir"); 
     unmarshaller.setSchema(schemaFactory.newSchema(new File(directory, schemaFile))); 
     return clazz.cast(unmarshaller.unmarshal(new File(directory, file))); 
    } catch (final Exception ex) { 
     ex.printStackTrace(); 
    } 
    System.exit(1); 
    return null; 
} 

을 내가 같이 사용 :

private static final Primitives primitives = readXML("primitives.xml", "primitives.xsd", Primitives.class); 

내 질문은 그게이 Unmarshaller에 사용자 지정 유효성 검사기를 추가 할 수있다? 무슨 말인지하면 Foo라는 complexType이 있다고 가정합니다. 그리고 나는 내가 XSD 파일에 설명 할 수없는 그 몇 가지 검증을 만들고 싶어, 그래서 이런 식으로 뭔가를하고 싶지 :

unmarshaller.setCustomValidator(Foo.class, new MyCustomValidator()); 

그래서 MyCustomValidator가 호출 될 때마다 JAXB는 푸를 읽습니다. 또는 xsd 파일에서 일부 유효성 검사를 설명 할 수없는 경우 JAXB 읽기가 완료된 후에 구문 분석 된 클래스의 유효성을 검사해야합니다.

아, btw ... xjd를 사용하여 xsd에서 JAXB 클래스를 생성했습니다.

+0

나는 cutom validator가 필요하다고 말했다. schema.newValidator()는 xsd에 대해 유효성을 검사합니다. 나는 xsd에 정의 된 것보다 다른 검증을하고 싶다. – ffddani

답변

0

유효성 검사 규칙을 xsd에 설명 할 수 없다면 JAXB의 범위를 벗어나는 것입니다. 그러나 클래스를 기반으로 사용자 정의 유효성 검사기 객체를 얻을 수있는 구조를 고안하는 경우 캡슐화 품질을 유지하기 위해 메소드 끝에 해당 논리를 추가 할 수 있습니다.

관련 문제