我有以下结构:
@XMLTransient
public abstract class Foo {
protected String name;
}
@XmlRootElement
@XmlType(propOrder={"name"})
public class BarX extends Foo {
public String getXThing() {
return name;
}
public void setXThing(String thing) {
name = thing;
}
}
@XmlRootElement
@XmlType(propOrder={"name"})
public class BarY extends Foo {
public String getYBlah() {
return name;
}
public void setYBlah(String blah) {
name = blah;
}
}
在我需要BarX而不是name
标记thing
的XML中,对于BarY,我希望blah
代替name
。有可能吗?我怎么能得到这个?
答案 0 :(得分:1)
您可以执行以下操作(您已经非常接近):
<强>富强>
package forum11340316;
import javax.xml.bind.annotation.XmlTransient;
@XmlTransient
public abstract class Foo {
protected String name;
}
<强> BarX 强>
package forum11340316;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlType(propOrder={"XThing"})
public class BarX extends Foo {
@XmlElement(name="thing")
public String getXThing() {
return name;
}
public void setXThing(String thing) {
name = thing;
}
}
<强> BARY 强>
package forum11340316;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlType(propOrder={"YBlah"})
public class BarY extends Foo {
@XmlElement(name="blah")
public String getYBlah() {
return name;
}
public void setYBlah(String blah) {
name = blah;
}
}
<强>演示强>
package forum11340316;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(BarX.class, BarY.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
BarX barX = new BarX();
barX.setXThing("XThing");
marshaller.marshal(barX, System.out);
BarY barY = new BarY();
barY.setYBlah("YBlah");
marshaller.marshal(barY, System.out);
}
}
<强>输出强>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<barX>
<thing>XThing</thing>
</barX>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<barY>
<blah>YBlah</blah>
</barY>
了解更多信息