Reputation: 1100
Easily switch between
<root>
<child>
<prop1>..</prop1>
<prop2>..</prop2>
</child>
<root>
and
<root>
<child>
<prop1>..</prop1>
<prop2>..</prop2>
<prop3>..</prop3>
<prop4>..</prop4>
</child>
</root>
@XmlRootElement(name= "root")
public class Root {
@XmlElement(name="child")
public Child child
}
@XmlRootElement(name= "root")
public class ExtendedRoot extends Root {
@XmlElement(name="child")
public ExtendedChild child
}
@XmlTransient
public class Child {
// prop1, prop2
}
@XmlType(propOrder = {"prop1", "prop3","prop4", "prop2"})
public class ExtendedChild extends Child {
// prop3, prop4
}
System.setProperty("javax.xml.bind.context.factory", "org.eclipse.persistence.jaxb.JAXBContextFactory")
Class clazz = extendChild ? ExtendedRoot.class : Root.class;
JAXBContext jc = JAXBContext.newInstance(clazz);
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(formattedJob, tempFile);
<root>
<child xs:type="ExtendedChild">
<prop1>..</prop1>
<prop2>..</prop2>
<prop3>..</prop3>
<prop4>..</prop4>
</child>
</root>
How can I exclude this xs:type=...
from the child
tag?
Upvotes: 1
Views: 29
Reputation: 420
The xs:type
is used here because the value of the child
property is polymorphic. Without it JAXB doesn't have a chance to decide which class to use when reading your own XML documents. JAXB isn't that clever to first introspect the element and then select the best fitting class.
But there are some other points while reading XML:
Are you aware, that ExtendedRoot
has two properties named child
(the one inherited from Root
, super.child and its own, this.child)? Since ExtendedChild
is a Child
also an ExtendedChild
may be stored to either of the two properties:
ExtendedChild
to Root.child
there is no necessity for ExtendedRoot.child
. Without this there is even no necessity for ExtendedRoot
in this example.If you insist on keeping ExtendedRoot
be aware that JAXB can't decide wether to use Root
or ExtendedRoot
if it stumbles about a root
element.
Upvotes: 1