Lets say I have the following POJO class, which I want to marshal using JAXB
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
Class Employee {
private String firstName;
private String lastName;
private int age;
}
Now I am marshaling an instance of Employee class using following code snippet
JAXBContext jc = JAXBContext.newInstance(Employee.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
OutputStream os = new FileOutputStream("C:\\employee.xml")
marshaller.marshal(employee, os);
The generated XML looks like
<Employee>
<firstName>Mark</firstName>
<lastName>Smith</lastName>
<age>30</age>
</Employee>
Question : I don't want the default Employee tag around employee data. ie
I want output as following
<firstName>Mark</firstName>
<lastName>Smith</lastName>
<age>30</age>
How to achieve this?
Not sure what are you asking. XML document must contain root element. You can change it using QName (example below), but it must exist.
JAXBContext jc = JAXBContext.newInstance(Employee.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
QName qName = new QName("", "whatever");
JAXBElement<Employee> newRootEmployee = new JAXBElement<Employee>(qName, Employee.class, employee);
OutputStream os = new FileOutputStream("C:\\employee.xml")
marshaller.marshal(newRootEmployee , os);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.