我有两个类:A和Test,它们是在diffenent .java文件中定义的。类测试作为类型A的字段。现在我需要能够对这两个类进行编组/解组,因此我需要将XMLRootElement放到这两个类中。可能吗?或者我需要一些包装吗? Coudl在谷歌找不到任何东西。
电贺, 杰夫
答案 0 :(得分:0)
这当然是可能的,你不需要任何类型的包装器。这是一个例子:
ItemA.java
package answer;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "ItemA")
@XmlAccessorType(value = XmlAccessType.FIELD)
public class ItemA {
private ItemB One = new ItemB();
private ItemB Two = new ItemB();
}
ItemB.java
package answer;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "ItemB")
@XmlAccessorType(value = XmlAccessType.FIELD)
public class ItemB {
private int One = 1;
private int Two = 2;
}
证明这是有效的
package answer;
import javax.xml.bind.JAXB;
import java.io.StringWriter;
public class Test {
public static void main(String[] args) {
ItemA itemA = new ItemA();
ItemB itemB = new ItemB();
StringWriter sw1 = new StringWriter();
JAXB.marshal(itemA, sw1);
System.out.println(sw1.toString());
StringWriter sw2 = new StringWriter();
JAXB.marshal(itemB, sw2);
System.out.println(sw2.toString());
}
}