Created
July 31, 2019 08:38
-
-
Save kdkanishka/2c61b4438c72b06398f7fb374a6208e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package jaxb; | |
import javax.xml.bind.JAXBContext; | |
import javax.xml.bind.JAXBException; | |
import javax.xml.bind.Marshaller; | |
import javax.xml.bind.annotation.XmlElement; | |
import javax.xml.bind.annotation.XmlElementWrapper; | |
import javax.xml.bind.annotation.XmlRootElement; | |
import javax.xml.bind.annotation.XmlValue; | |
import java.io.ByteArrayOutputStream; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class Test { | |
public static void main(String[] args) throws JAXBException { | |
List<Employee> employees = new ArrayList<Employee>(); | |
employees.add(new Employee("ABC")); | |
employees.add(new Employee("DEF")); | |
Metadata metadata = new Metadata("CSLWORLD", employees); | |
JAXBContext jaxbContext = JAXBContext.newInstance(Metadata.class); | |
Marshaller marshaller = jaxbContext.createMarshaller(); | |
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); | |
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); | |
marshaller.marshal(metadata, byteArrayOutputStream); | |
String resultingXml = new String(byteArrayOutputStream.toByteArray()); | |
System.out.println(resultingXml); | |
} | |
} | |
@XmlRootElement | |
class Metadata { | |
private String name; | |
private List<Employee> employees; | |
public Metadata() { | |
} | |
public Metadata(String name, List<Employee> employees) { | |
this.name = name; | |
this.employees = employees; | |
} | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
@XmlElementWrapper(name="employees") | |
@XmlElement(name="employee") | |
public List<Employee> getEmployees() { | |
return employees; | |
} | |
public void setEmployees(List<Employee> employees) { | |
this.employees = employees; | |
} | |
} | |
@XmlRootElement(name="employee") | |
class Employee { | |
private String name; | |
public Employee() { | |
} | |
public Employee(String name) { | |
this.name = name; | |
} | |
@XmlValue | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result :