有效值我的POJO的對象樹表示XML架構。這是用以下jaxb
ant腳本創建的。的SAXParseException:值不是「日期」
我想根據模式驗證根POJO及其子實體缺少的屬性。
我的代碼如下:(試行/省略catch塊,靈感來自SO質疑How to validate against schema in JAXB 2.0 without marshalling?)
public boolean validateAgainstSchema(Pojo pojo)
{
JAXBContext jc;
jc = JAXBContext.newInstance(Pojo.class);
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new ClassPathResource("schema.xsd").getFile());
Marshaller marshaller = jc.createMarshaller();
marshaller.setSchema(schema);
marshaller.marshal(schema, new DefaultHandler());
return true;
}
我的一個屬性(pojo.childEntity.someAttribute
)是date
XSD
<xsd:attribute name="some_date" use="required">
<xsd:simpleType>
<xsd:restriction base="xsd:date" />
</xsd:simpleType>
</xsd:attribute>
的Java
@XmlAttribute(name = "someDate", required = true)
protected XMLGregorianCalendar someDate;
它從來自另一POJO(一個是與Hibernate映射)一個java.util.Date
對象進行填充。
private static final XMLGregorianCalendar dateToCalendar(Date date)
{
if (date == null)
return null;
try
{
GregorianCalendar c = new GregorianCalendar();
c.setTime(date);
return DatatypeFactory.newInstance()
.newXMLGregorianCalendar(c);
}
catch (DatatypeConfigurationException e)
{
e.printStackTrace();
return null;
}
}
唯一的例外是:
javax.xml.bind.MarshalException
- with linked exception:
[org.xml.sax.SAXParseException: cvc-datatype-valid.1.2.1: '2001-05-11T00:00:00.000+02:00' is not a valid value for 'date'.]
這看起來像JAXB試圖設置日期和時間必須只攜帶日期字段,XMLGregorianCalendard是一個簡單的日期時間的容器。
的問題是:是什麼原因造成的錯誤?怎麼修?
事實更復雜(我認爲這並不重要):我從日期填充GregCalendar –
@djechelon - 我已經更新了我的答案應該有所幫助的信息。 –
好吧,因爲我有XmlGregorianCalendars的loooooooooooooooooooooooooooooooooots有沒有辦法告訴XJC添加xmlSchemaType屬性到所有的XGC? –