Reputation:
I'm using JAXB to unmarshal some xml into an object(s).
I have a class which inherit from an abstract class. I've marked the abstract class as @XmlTransient. Then using XMLType PropOrder I can access the properties in the abstract class like so:
@XmlType( propOrder = { "id"...
Cool. Problem is sometimes it isn't an element that I want to access but rather an attribute. Normally you would define such a property using @XMLAttribute to indicate the value is stored in an xml attribute and not an element. But given the fact that I've already used XMLTransient on the abstract class where 'id' is defined, JAXB complains when I try to mark the field as @XMLAttribute.
JAXB is complaining that I'm trying to access/return two fields of with the same name.
Can anyone please point me in the right direction? I'm building for GAE so I dn't really want to use any other libraries.
Thanks in advance!
Upvotes: 1
Views: 1948
Reputation: 149017
Below are a couple of things you can do:
Foo
You can annotate the property on the parent class with @XmlAttribute
.
import javax.xml.bind.annotation.*;
@XmlTransient
public class Foo {
private String att1;
private String att2;
@XmlAttribute
public String getAtt1() {
return att1;
}
public void setAtt1(String att1) {
this.att1 = att1;
}
public String getAtt2() {
return att2;
}
public void setAtt2(String att2) {
this.att2 = att2;
}
}
Bar
You can override the property on the subclass and annotate it with @XmlAttribute
.
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Bar extends Foo {
@Override
@XmlAttribute
public String getAtt2() {
return super.getAtt2();
}
@Override
public void setAtt2(String att2) {
super.setAtt2(att2);
}
}
Demo
Here is some demo code you can run to show that everything works.
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Bar.class);
Bar bar = new Bar();
bar.setAtt1("a");
bar.setAtt2("b");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(bar, System.out);
}
}
Output
Below is the output from running the demo code:
<?xml version="1.0" encoding="UTF-8"?>
<bar att1="a" att2="b"/>
Upvotes: 2