java – JAXB – 如何根据XML值设置XML元素的xsi:type?

我必须生成一个xml元素,它可以具有任何“基本类型”(xsd:string,xsd:boolean等)作为值.例子:

<field xsi:type="xsd:string" name="aString">String Value</field>
<field xsi:type="xsd:date" name="aDate">2011-10-21</field>
...

所以,我试过两个实现:

public class Field {
    @XmlAttribute
    private String name;

    @XmlValue
    Object value;
}

和……

public class Field<T> {
    @XmlAttribute
    private String name;

    @XmlValue
    T value;
}

我正在测试这个:

Marshaller marshaller = JAXBContext.newInstance(Field.class).createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE);

Field field = new Field();
field.name = "name";
field.value = "value";

ByteArrayOutputStream stream = new ByteArrayOutputStream();
marshaller.marshal(field, new PrintWriter(stream));
System.out.println(stream);

但是当我尝试实例化JAXBContext时,我得到了这个NullPointerException.

java.lang.NullPointerException
at com.sun.xml.bind.v2.runtime.reflect.TransducedAccessor.get(TransducedAccessor.java:165)
at com.sun.xml.bind.v2.runtime.property.ValueProperty.<init>(ValueProperty.java:77)
at com.sun.xml.bind.v2.runtime.property.PropertyFactory.create(PropertyFactory.java:106)
at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:179)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:515)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:330)
at 

这个想法是允许字段元素的模式验证(在模式中定义必须在每个实例中设置其类型).所以,即使这是一个Bug(或不是)…… JAXB如何将正确的xsi:type放到这个字段实例中?我在这里错过了一个概念?

我知道问题可能是@XmlValue的使用,因为这个限制(来自javadoc):

  • At most one field or property can be annotated with the @XmlValue annotation.
  • @XmlValue can be used with the following annotations: XmlList. However this is redundant since XmlList maps a type to a simple schema type that derives by list just as XmlValue would.
  • If the type of the field or property is a collection type, then the collection item type must map to a simple schema type.
  • If the type of the field or property is not a collection type, then the type must map to a XML Schema simple type.

…因为Object或泛型T不一定是XML Schema简单类型,这种方法似乎不是正确的…

提前致谢 …

最佳答案 我已经确认了您在JAXB的参考和
EclipseLink JAXB (MOXy)实现中看到的问题.您看到的问题是由于使用了@XmlValue.如果value属性被映射为@XmlElement,您将看到xsi:type属性按预期显示.

我在EclipseLink JAXB(MOXy)中输入了以下错误来跟踪此问题:

> https://bugs.eclipse.org/361689

根据您的域模型的样子,您可能会对EclipseLink JAXB(MOXy)中的@XmlPath扩展感兴趣:

> http://blog.bdoughan.com/2011/03/map-to-element-based-on-attribute-value.html

UPDATE

此问题现已在EclipseLink 2.3.3和EclipseLink 2.4.0中得到修复.从2012年3月17日开始,可以在这些流中使用此修复程序,可以从以下位置获取:

> http://www.eclipse.org/eclipselink/downloads/nightly.php

点赞