JaxB绑定XMLGregorianCalendar

时间:2011-07-14 05:57:46

标签: java binding jaxb

将不正确的日期格式绑定到XMLGregorianCalendar时,JaxB不会抛出异常。相反,它指定null。可能是什么问题?

@XmlAttribute(name = "travelEndDate", required = true)
@XmlSchemaType(name = "date")
protected XMLGregorianCalendar travelEndDate;

<xs:complexType name="SearchCriteria">
<xs:attribute name="travelStartDate" type="xs:date" use="required"/>
<xs:attribute name="travelEndDate" type="xs:date" use="required"/>
</xs:complexType>

3 个答案:

答案 0 :(得分:4)

注意:我是EclipseLink JAXB (MOXy)负责人,也是JAXB 2.X(JSR-222)专家组的成员。

这种行为在JAXB实现之间会有所不同。例如,如果值不正确,MOXy将抛出以下异常:

Exception in thread "main" javax.xml.bind.UnmarshalException
 - with linked exception:
[Exception [EclipseLink-3003] (Eclipse Persistence Services - 2.4.0.qualifier): org.eclipse.persistence.exceptions.ConversionException
Exception Description: Incorrect date format: [2011-02-50] (expected [YYYY-MM-DD])]
    at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:225)
    at forum254.Demo.main(Demo.java:18)
Caused by: Exception [EclipseLink-3003] (Eclipse Persistence Services - 2.4.0.qualifier): org.eclipse.persistence.exceptions.ConversionException
Exception Description: Incorrect date format: [2011-02-50] (expected [YYYY-MM-DD])
    at org.eclipse.persistence.exceptions.ConversionException.incorrectDateFormat(ConversionException.java:103)
    at org.eclipse.persistence.internal.oxm.XMLConversionManager.convertStringToXMLGregorianCalendar(XMLConversionManager.java:689)
    at org.eclipse.persistence.internal.oxm.XMLConversionManager.convertObjectToXMLGregorianCalendar(XMLConversionManager.java:278)
    at org.eclipse.persistence.internal.oxm.XMLConversionManager.convertObject(XMLConversionManager.java:249)
    at org.eclipse.persistence.oxm.XMLField.convertValueBasedOnSchemaType(XMLField.java:712)

解决方法

要在任何JAXB实现上报告错误,您可以在unmarshaller上设置XML架构以执行验证:

或者您可以自己实现XmlAdapter来控制转换(并在必要时抛出异常):

答案 1 :(得分:1)

也许此链接对您有所帮助:

http://eskatos.wordpress.com/2007/11/24/jaxb-custom-binding-for-joda-time/

它描述了使用自定义Java数据类型(此处为:JodaTime)处理XML中的日期

答案 2 :(得分:0)

使用它,它将捕获异常:

try {
   String date = "your date here"
   XMLGregorianCalendar xmlGCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(date);
    } catch (DatatypeConfigurationException ex) {
       //DO STUFF
      }

更新

添加代码后,我不确定你会怎么做到这一点。为此,我认为你需要进行空检查,并按照自己的意愿行事。