如何从XML生成JAXB bean,自定义JAXB编组

我想在JAXB中自定义日期的编组.这是已经问过 question的变种.我认为我会使用XMLAdapter,正如 this answer问题所指定的那样.

但我不能完全这样做,因为我反过来,从.XSD生成JAXB bean – 我无法向JAXB bean添加注释,因为它们是生成代码.

我试过调用Marshaller.setAdapter(),但没有运气.

final Marshaller marshaller = getJaxbContext().createMarshaller();
            marshaller.setSchema(kniSchema);
            marshaller.setAdapter(new DateAdapter());
            ...
            private static class DateAdapter extends XmlAdapter<String,XMLGregorianCalendar> {
            @Override
            public String marshal(XMLGregorianCalendar v) throws Exception {
              return "hello"; //Just a test to see if it's working
            }
            @Override
            public XMLGregorianCalendar unmarshal(String v) throws Exception {
              return null; // Don't care about this for Now
            }
}

生成的JAXB bean的相关部分如下所示:

@XmlSchemaType(name = "date")
    protected XMLGregorianCalendar activeSince;

当我这样做时,认日期/ XMLGregorianCalendar编组发生了什么.就好像我没有做到这一切.

任何帮助表示赞赏.

谢谢,

查尔斯

在XJC生成的Java上更改绑定类型的首选方法是使用绑定自定义.

https://jaxb.dev.java.net/guide/Using_different_datatypes.html

JAXB has a built-in table that
determines what Java classes are used
to represent what XML Schema built-in
types,but this can be customized.

One of the common use cases for
customization is to replace the
XMLGregorianCalendar with the
friendlier Calendar or Date.
XMLGregorianCalendar is designed to be
100% compatible with XML Schema’s
date/time system,such as providing
infinite precision in sub-seconds and
years,but often the ease of use of
those familiar Java classes win over
the precise compatibility.

页面并未告诉您如何实际连接自定义,因此请查看如何执行此操作:

http://jaxb.java.net/tutorial/section_5_6_1-Overriding-the-Datatype.html#Overriding%20the%20Datatype

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念