Reputation: 1143
I have the following class
@XmlRootElement
public class Test {
@XmlTransient
private String abc;
@XmlElement
private String def;
}
My question is, I want to use this class to generate two kinds of XMLs
1. With <abc>
2. without <abc>
I can achieve the second one since I have marked it as transient. Is there any way so that if I mark "abc" as @XMLElement
and can ignore it while marshalling?
Thanks in advance
Upvotes: 1
Views: 6215
Reputation: 149017
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
You may be interested in the @XmlNamedObjectGraph
extension we have added in EclipseLink 2.5.0. It allows you to define multiple views on your domain model. You can try this out today using a nightly build:
Below I'll give an example:
Test
The @XmlNamedObjectGraph
annotation is used to define subsets of the object graph that can be used when marshalling and unmarshalling.
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.*;
@XmlNamedObjectGraph(
name="only def",
attributeNodes = {
@XmlNamedAttributeNode("def")
}
)
@XmlRootElement
public class Test {
private String abc;
private String def;
public String getAbc() {
return abc;
}
public void setAbc(String abc) {
this.abc = abc;
}
public String getDef() {
return def;
}
public void setDef(String def) {
this.def = def;
}
}
Demo
The MarshallerProperties.OBJECT_GRAPH
can be used to specify which object graph should be marshallled.
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.MarshallerProperties;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Test.class);
Test test = new Test();
test.setAbc("FOO");
test.setDef("BAR");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Marshal the Entire Object
marshaller.marshal(test, System.out);
// Marshal Only What is Specified in the Object Graph
marshaller.setProperty(MarshallerProperties.OBJECT_GRAPH, "only def");
marshaller.marshal(test, System.out);
}
}
Output
Below is the output from running the demo code. The first time the instance of Test
is marshalled it contains all the properties and the second time just the def
property.
<?xml version="1.0" encoding="UTF-8"?>
<test>
<abc>FOO</abc>
<def>BAR</def>
</test>
<?xml version="1.0" encoding="UTF-8"?>
<test>
<def>BAR</def>
</test>
For More Information
Upvotes: 2