如何在子类上使用JAXB @XmlValue? [英] How do I use JAXB @XmlValue on a subclass?

查看:133
本文介绍了如何在子类上使用JAXB @XmlValue?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要这样的XML:

<simple>Foo</simple>

我可以通过如下所示的JAXB类成功完成此操作:

I can do this successfully via a JAXB class that looks like this:

@XmlRootElement(name="simple")
class Simple {
    @XmlValue
    public String contents;
}

但是现在我需要让Simple类成为另一个类的子类所以:

But now I need to make the Simple class be a subclass of another class like so:

@XmlRootElement(name="simple")
class Simple extends OtherClass {
    @XmlValue
    public String contents;
}

失败并带有 @XmlValue不允许派生另一个类的类。我不能轻易地重构超类(因为我们在包装类上使用@XmlElementRef的方式)。有没有一种解决方法可以让我注释我的子类来生成那个简单的XML?

That fails with @XmlValue is not allowed on a class that derives another class. I can't easily refactor the superclass away (because of the way we're using @XmlElementRef on a wrapper class). Is there a workaround that will let me annotate my subclass to generate that simple XML?

推荐答案

注意:我是 EclipseLink JAXB(MOXy) 的主管, JAXB 2(JSR-222)的成员专家组。

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.

MOXy支持此用例,JAXB RI也应支持IMHO:

This use case is supported by MOXy, and IMHO should be supported by the JAXB RI as well:

简单

此类有一个用 @XmlValue 映射的字段, extends OtherClass

This class has a field mapped with @XmlValue and extends OtherClass:

package forum809827;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;

@XmlRootElement(name="simple")
class Simple extends OtherClass {

    @XmlValue
    // @XmlValueExtension
    // As of moxy 2.6, XmlValueExtension needs to be added for this to work
    public String contents;

}

OtherClass

这是超类。在MOXy中,只要超类没有与XML元素的任何映射,子类就可以使用 @XmlValue 映射字段/属性:

This is the super class. In MOXy the subclass can map a field/property with @XmlValue as long as the super class does not have any mappings to an XML element:

package forum809827;

import javax.xml.bind.annotation.XmlAttribute;

public class OtherClass {

    @XmlAttribute
    public String other;

}

演示

package forum809827;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Simple.class);

        Simple simple = new Simple();
        simple.contents = "FOO";
        simple.other = "BAR";

        Marshaller marshaller = jc.createMarshaller();
        marshaller.marshal(simple, System.out);
    }

}

输出

<?xml version="1.0" encoding="UTF-8"?>
<simple xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" other="BAR">FOO</simple>

有关将MOXy指定为JAXB提供商的更多信息

  • http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html

这篇关于如何在子类上使用JAXB @XmlValue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆