我想要像这样的XML:
<simple>Foo</simple>
Run Code Online (Sandbox Code Playgroud)
我可以通过看起来像这样的JAXB类成功完成此操作:
@XmlRootElement(name="simple")
class Simple {
@XmlValue
public String contents;
}
Run Code Online (Sandbox Code Playgroud)
但是现在我需要使Simple类成为另一个类的子类,如下所示:
@XmlRootElement(name="simple")
class Simple extends OtherClass {
@XmlValue
public String contents;
}
Run Code Online (Sandbox Code Playgroud)
失败了,@XmlValue is not allowed on a class that derives another class.我无法轻易地重构超类(因为我们在包装类上使用@XmlElementRef的方式).有没有一种解决方法可以让我注释我的子类来生成那个简单的XML?
注意: 我是EclipseLink JAXB(MOXy)的负责人,也是JAXB 2(JSR-222)专家组的成员.
MOXy支持此用例,JAXB RI也应支持IMHO:
简单
该类有一个映射的字段,@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;
}
Run Code Online (Sandbox Code Playgroud)
OtherClass
这是超级课程.在MOXy中@XmlValue,只要超类没有与XML元素的任何映射,子类就可以映射字段/属性:
package forum809827;
import javax.xml.bind.annotation.XmlAttribute;
public class OtherClass {
@XmlAttribute
public String other;
}
Run Code Online (Sandbox Code Playgroud)
演示
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);
}
}
Run Code Online (Sandbox Code Playgroud)
产量
<?xml version="1.0" encoding="UTF-8"?>
<simple xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" other="BAR">FOO</simple>
Run Code Online (Sandbox Code Playgroud)
有关将MOXy指定为JAXB提供程序的更多信息
| 归档时间: |
|
| 查看次数: |
11009 次 |
| 最近记录: |