how can I map (via JAXB in java 1.6) Collection to XML and from XML, where
class mapping{
@XmlElementWrapper(name="list")
@XmlElement(name="item")
Collection<A> list;
}
abstract class A{
}
class B extends A{
public String onlyB;
}
class C extends A{
public String onlyC;
}
a would like to see XML like this:
<something> (doesnt matter, I'm using it in another structure)
<list>
<item xsi:type="b"><onlyB>b</onlyB></item>
<item xsi:type="c"><onlyC>c</onlyC></item>
</list>
</something>
its working if I have
class mapping{
@XmlElement(name="item")
A item;
}
I already tried xmlelementref, but with no success
and I dont want to use @XmlElements({@XmlElement ...})
because other project which are using this can add derived class from A
Your mapping appears to be correct. You need to ensure that the B
and C
classes are included when you create the JAXBContext. One way to accomplish this is to use @XmlSeeAlso
.
@XmlSeeAlso(B.class, C.class)
abstract class A{
}
Below is an example of using xsi:type
to represent inheritance in the domain model with JAXB:
@XmlElementRef
is used when you want to represent inheritance using the XML schema concept of substitution groups:
XmlElements
corresponds to the choice structure in XML schema:
FULL EXAMPLE
Below is a complete example:
Mapping
package forum7672121;
import java.util.Collection;
import javax.xml.bind.annotation.*;
@XmlRootElement(name="something")
@XmlAccessorType(XmlAccessType.FIELD)
class Mapping{
@XmlElementWrapper(name="list")
@XmlElement(name="item")
Collection<A> list;
}
A
package forum7672121;
import javax.xml.bind.annotation.XmlSeeAlso;
@XmlSeeAlso({B.class, C.class})
abstract class A{
}
B
package forum7672121;
class B extends A{
public String onlyB;
}
C
package forum7672121;
class C extends A{
public String onlyC;
}
Demo
package forum7672121;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Mapping.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum7672121/input.xml");
Mapping mapping = (Mapping) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(mapping, System.out);
}
}
input.xml/Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<something>
<list>
<item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="b">
<onlyB>b</onlyB>
</item>
<item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="c">
<onlyC>c</onlyC>
</item>
</list>
</something>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With