Reputation: 2258
I need to create some xml to send off to another application in the below format and I'm trying to use jaxb. There is always only 1 occurrence of bar. Is there a way to do this or is it invalid xml because it has 2 root elements and the other application will need to change how it accepts the xml?
<FOO>
<BAR>
<id>1</id>
<POINTS>111</POINTS>
<CODE>123</CODE>
</BAR>
</FOO>
Upvotes: 1
Views: 1354
Reputation: 149007
Below are a couple of approaches:
Standard JAXB
The following will work with any JAXB implementation (Metro, MOXy, JaxMe, etc). You could create the element "FOO", and then marshal your instance of Bar into it. The code below how to demonstrate this using StAX (it could also be done with DOM or SAX):
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
public class Demo {
public static void main(String[] args) throws Exception {
XMLOutputFactory xof = XMLOutputFactory.newFactory();
XMLStreamWriter xsw = xof.createXMLStreamWriter(System.out);
xsw.writeStartDocument();
xsw.writeStartElement("FOO");
Bar bar = new Bar();
bar.setId(1);
bar.setPoints(111);
bar.setCode(123);
JAXBContext jc = JAXBContext.newInstance(Bar.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.marshal(bar, xsw);
xsw.writeEndElement();
xsw.writeEndDocument();
xsw.close();
}
}
EclipseLink JAXB (MOXy)
If you happen to be using EclipseLink JAXB (MOXy), then you can use the @XmlPath extension (I'm the MOXy tech lead). Your Bar class would look like:
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlRootElement(name="FOO")
@XmlType(propOrder={"id", "points", "code"})
public class Bar {
private int id;
private int points;
private int code;
@XmlPath("BAR/id/text()")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@XmlPath("BAR/POINTS/text()")
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
@XmlPath("BAR/CODE/text()")
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
For more information see:
Upvotes: 1