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

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

String Value

2011-10-21

...

所以,我试过两个实现:

public class Field {

@XmlAttribute

private String name;

@XmlValue

Object value;

}

和……

public class Field {

@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.(ValueProperty.java:77)

at com.sun.xml.bind.v2.runtime.property.PropertyFactory.create(PropertyFactory.java:106)

at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.(ClassBeanInfoImpl.java:179)

at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:515)

at com.sun.xml.bind.v2.runtime.JAXBContextImpl.(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)中输入了以下错误来跟踪此问题:

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

UPDATE

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

标签:java,xml,xml-serialization,jaxb

来源: https://codeday.me/bug/20190704/1378976.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值