2011-11-11 38 views
11

我想这样的XML:如何在子类上使用JAXB @XmlValue?

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

但现在我需要做的简单类是另一个子类:

<simple>Foo</simple> 

我可以通过JAXB类,看起来像这样成功地做到这一点类像这样:

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

失败与@XmlValue is not allowed on a class that derives another class.我不能轻易重构的超远(因为这样,我们正在使用@XmlE在包装类上的lementRef)。有没有解决方法可以让我注释我的子类来生成这个简单的XML?

回答

7

备注:我是EclipseLink JAXB (MOXy)的领导和JAXB 2 (JSR-222)专家组的成员。

此使用情况由MOXY支撑,并且IMHO应由JAXB RI以及被支撑:

简单

此类具有与@XmlValue映射到的字段和延伸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; 

} 

其他类

这是超级班。在MOXY子类可以字段/属性映射与@XmlValue只要超级类不具有任何映射到XML元素:

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> 

有关指定MO的更多信息XY为您的JAXB提供

+0

哇,感谢详细的例子!不幸的是,我的应用程序容器(Karaf)使用ServiceMix中的jaxb-impl/jaxb-xjc,我相信它很难切换。 –

+0

@ChrisDolan - 这取决于您的应用程序环境。 JAXB提供者可以在模型级配置。在以下文章中,默认情况下在使用JAXB RI的GlassFish服务器中使用MOXy:http://blog.bdoughan.com/2010/08/creating-restful-web-service-part-35.html –

+4

@ChrisDolan - 当使用JAXB RI时,您可能会将'OtherClass'标记为@XmlTransient:http://blog.bdoughan.com/2011/06/ignoring-inheritance-with-xmltransient.html –

12

接受的答案并没有为我工作。作为描述,但我还需要到@XmlTransient添加到超

+0

我也必须添加'@XmlAccessorType(XmlAccessType.NONE)'到我的子类,否则我会得到错误'如果一个类有'@XmlElement'属性,它不能有'@XmlValue'属性。希望这可以帮助某人。 –

0

我能够通过改变@XmlValue@XmlMixed和改变变量列表,使这项工作

一切都很好。最终的类应如下所示。

@XmlRootElement(name="simple") 
class Simple extends OtherClass { 
    @XmlMixed 
    public List<String> contents; 
} 
0

这个问题发生在我身上,花了我一点时间。 由于布莱斯Doughan 我通过他的博客,并找到答案

  1. 你必须添加一个 jaxb.properties与javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory 在同一个包文件,以便使用莫西

  2. 加MOXY到Maven依赖或添加MOXY罐子

    <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.moxy</artifactId> <version>2.5.0</version> </dependency>

  3. 则全部设置 我这里样品,你可以去,虽然我的项目,看看 https://github.com/cicidi/HelloCCD/tree/master/Jaxb