I have below employee.xml which I am trying to convert to Java Object using JAXB. I am getting null value here, please guide me what I am missing here or doing wrong.
I am not familiar with JAXB and namespace <employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schema.cs.csg.com/cs/ib/cpm"> I thing I am missing some annotation or not using it properly.
Output:
Employee [id=null, firstName=null, lastName=null, department=null]
employee.xml
<?xml version="1.0"?>
<employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlnx="http://schema.cs.csg.com/cs/ib/cpm">
<department>
<id>101</id>
<name>IT</name>
</department>
<firstName>Rakesh</firstName>
<id>1</id>
<lastName>Yadav</lastName>
</employee>
Employee.java
package com.cs.xmltojava
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "employee", namespace="http://schema.cs.csg.com/cs/ib/cpm")
#XmlAccessorType(XmlAccessType.PROPERTY)
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String firstName;
private String lastName;
private Department department;
public Employee() {
super();
}
public Employee(int id, String fName, String lName, Department department) {
super();
this.id = id;
this.firstName = fName;
this.lastName = lName;
this.department = department;
}
//Setters and Getters
public Integer getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
#Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", department="+ department + "]";
}
}
Department.java
package com.cs.xmltojava
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "department", namespace="http://schema.cs.csg.com/cs/ib/cpm")
#XmlAccessorType(XmlAccessType.PROPERTY)
public class Department implements Serializable {
private static final long serialVersionUID = 1L;
Integer id;
String name;
public Department() {
super();
}
public Department(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
//Setters and Getters
public Integer getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Department [id=" + id + ", name=" + name + "]";
}
}
EmployeeMain.java
package com.cs.xmltojava
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class EmployeeMain {
public static void main(String[] args) throws Exception {
File xmlFile = new File("employee.xml");
JAXBContext jaxbContext;
try
{
jaxbContext = JAXBContext.newInstance(Employee.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Employee employee = (Employee) jaxbUnmarshaller.unmarshal(xmlFile);
System.out.println(employee);
}
catch (JAXBException e)
{
e.printStackTrace();
}
}
}
create package-info.java in your package and remove
namespace="http://schema.cs.csg.com/cs/ib/cpm" from #XmlRootElement.
package-info.java
#XmlSchema(
namespace="http://schema.cs.csg.com/cs/ib/cpm",
elementFormDefault=XmlNsForm.QUALIFIED
)
package com.cs.xmlparser;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
Related
I have this particular xml file(in that exact format) that I am trying to parse with JAXB
Because the properties are all on a single line it doesn't see them and returns all fields as null in my main function. How can I parse the xml correctly in it's format?
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee firstName="Asya" id="2" lastname="Olshansky"/>
</employees>
This is the code for employee
#XmlRootElement(name = "employee")
#XmlAccessorType (XmlAccessType.FIELD)
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String firstName;
private String lastName;
public Employee() {
super();
}
//Setters and Getters
#Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
Employees code:
#XmlRootElement(name = "employees")
#XmlAccessorType(XmlAccessType.FIELD)
public class Employees {
#XmlElement(name = "employee")
List<Employee> employees = null;
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> list) {
this.employees = list;
}
}
This is the Main execution:
public static void main(String[] args)
{
String fileName = "employee.xml";
jaxbXmlFileToObject(fileName);
}
private static void jaxbXmlFileToObject(String fileName) {
File xmlFile = new File(fileName);
JAXBContext jaxbContext;
try
{
jaxbContext = JAXBContext.newInstance(Employees.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Employees employees = (Employees) jaxbUnmarshaller.unmarshal(xmlFile);
for(Employee e: employees.getEmployees() )
System.out.println(e);
}
catch (JAXBException e)
{
e.printStackTrace();
}
}
Try:
Employee.java:
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String firstName;
private String lastName;
public Employee() {
super();
}
public Employee(Integer id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
#XmlAttribute(name="id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#XmlAttribute(name="firstName")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#XmlAttribute(name="lastname")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
Employees.java:
#XmlRootElement(name="employees")
public class Employees {
List<Employee> employees;
public Employees() {}
public Employees(List<Employee> employees) {
super();
this.employees = employees;
}
#XmlElement(name="employee")
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> list) {
this.employees = list;
}
}
Output:
Note:
No changes in Main.
Updated Employee and Employees class.
Added #XmlAttribute in Employee to map attribute names and getter/setters.
Added #XmlElement in Employees to map each employee element inside the employees tag and constructor also.
Im trying to build java object for xml by
java code
JAXBContext jaxbContext = JAXBContext.newInstance(Enfinity.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Enfinity enfinity = (Enfinity) jaxbUnmarshaller.unmarshal(xmlFile);
xml
<?xml version="1.0" encoding="UTF-8"?>
<enfinity xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dt="http://www.intershop.com/xml/ns/enfinity/6.5/core/impex-dt" xsi:schemaLocation="http://www.intershop.com/xml/ns/intershop/customer/impex/7.3 b2b_customer.xsd http://www.intershop.com/xml/ns/enfinity/6.5/core/impex-dt dt.xsd" major="6" minor="1" family="enfinity" branch="enterprise" build="1.0.299">
<customer id="34627">
<customer-type>SMB</customer-type>
<company-name>xxxxx & xxxxx</company-name>
<industry>Retail</industry>
<enabled>1</enabled>
<approval-status>1</approval-status>
<custom-attributes>
<custom-attribute name="CustomerPriceLevel" dt:dt="string">4</custom-attribute>
<custom-attribute name="FreeFreightThreshold" dt:dt="string">300.00</custom-attribute>
<custom-attribute name="ECOMCustomerId" dt:dt="string">xxxxxx</custom-attribute>
<custom-attribute name="BlockCreditCardPayment" dt:dt="boolean">true</custom-attribute>
<custom-attribute name="CustomLoad" dt:dt="string">true</custom-attribute>
</custom-attributes>
<users>
<user business-partner-no="xxxx">
<business-partner-no>xxxxx</business-partner-no>
<profile>
<first-name>xxxx</first-name>
<last-name>xxxx</last-name>
<email>xxx</email>
</profile>
<user-groups>
<user-group id="IG_SMBCustomers"/>
<user-group id="IG_RecurringUsers"/>
<user-group id="52"/>
</user-groups>
</user>
<user business-partner-no="xxxxx">
<business-partner-no>xxxxx</business-partner-no>
<profile>
<credentials>
<login>xxxxx.com</login>
<password encrypted="1">xxxxx</password>
<enabled>1</enabled>
<reminder-email>xxxxxx.com</reminder-email>
<password-creation-date>2019-03-28T06:37:29-07:00</password-creation-date>
</credentials>
<creation-date>2019-02-28T03:45:43-08:00</creation-date>
<phone-home>xxxxxx</phone-home>
<email>xxxxxxxxx.com</email>
<last-name>xxxxx</last-name>
<first-name>xxxxxx</first-name>
<custom-attributes>
<custom-attribute name="RoleID" dt:dt="string">APP_B2B_BUYER</custom-attribute>
</custom-attributes>
</profile>
</user>
</users>
when I try to get login from user tag even though value is there im getting null my poji looks like
Customer
package com.poc.highline;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "customer")
#XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
#XmlElement (name = "id")
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#XmlElement (name = "customer-type")
String customerType;
public String getCustomerType() {
return customerType;
}
public void setCustomerType(String customerType) {
this.customerType = customerType;
}
#XmlElement (name = "company-name")
String companyName;
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
#XmlElement (name = "industry")
String industry;
public String getIndustry() {
return industry;
}
public void setIndustry(String industry) {
this.industry = industry;
}
#XmlElement (name = "enabled")
String enabled;
public String getEnabled() {
return enabled;
}
public void setEnabled(String enabled) {
this.enabled = enabled;
}
#XmlElement (name = "approval-status")
String approvalStatus;
public String getApprovalStatus() {
return approvalStatus;
}
public void setApprovalStatus(String approvalStatus) {
this.approvalStatus = approvalStatus;
}
#XmlElement (name = "custom-attributes")
List<customAttributes> customAttributes;
public List<customAttributes> getCustomAttributes() {
return customAttributes;
}
public void setCustomAttributes(List<customAttributes> customAttributes) {
this.customAttributes = customAttributes;
}
#XmlElement (name = "users")
List<Users> users;
public List<Users> getUsers() {
return users;
}
public void setUsers(List<Users> users) {
this.users = users;
}
#XmlElement (name = "preferred-invoice-to-address")
PreferredInvoiceAddress invoiceAddress;
public PreferredInvoiceAddress getInvoiceAddress() {
return invoiceAddress;
}
public void setInvoiceAddress(PreferredInvoiceAddress invoiceAddress) {
this.invoiceAddress = invoiceAddress;
}
#XmlElement (name = "addresses")
List<Addresses> addresses;
public List<Addresses> getAddresses() {
return addresses;
}
public void setAddresses(List<Addresses> addresses) {
this.addresses = addresses;
}
}
This is users POJO class
Users
package com.poc.highline;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "users")
#XmlAccessorType(XmlAccessType.FIELD)
public class Users {
#XmlElement(name="user")
List<User> user;
public List<User> getUser() {
return user;
}
public void setUser(List<User> user) {
this.user = user;
}
}
this is the user POJO class
user
package com.poc.highline;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "user")
#XmlAccessorType(XmlAccessType.FIELD)
public class User {
#XmlElement(name = "business-partner-no")
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#XmlElement(name = "profile")
String profile;
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
#XmlElement(name = "credentials")
String credentials;
public String getCredentials() {
return credentials;
}
public void setCredentials(String credentials) {
this.credentials = credentials;
}
String login;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Im getting value in id but not in other variable refer the watchList
enfinity Enfinity (id=30)
customer ArrayList<E> (id=32)
[0] Customer (id=43)
addresses ArrayList<E> (id=45)
approvalStatus "1" (id=46)
companyName "xxxxx & xxxxx" (id=49)
customAttributes ArrayList<E> (id=50)
customerType "SMB" (id=51)
enabled "1" (id=52)
id null
industry "Retail" (id=53)
invoiceAddress PreferredInvoiceAddress (id=54)
users ArrayList<E> (id=56)
[0] Users (id=58)
user ArrayList<E> (id=60)
[0] User (id=62)
credentials null
email null
id "xxxxx" (id=65)
login null
profile "\n " (id=66)
[1] User (id=63)
credentials null
email null
id "xxxxx" (id=67)
login null
profile "\n " (id=68)
please help thanks in advance.
You are getting null for the Id of your customer because it's not an #XmlElement. Use #XmlAttribute instead.
For clarification:
<customer id="1">
<name>somename</name>
<customer>
id: #XmlAttribute
name: #XmlElement
somename: #XmlValue
Check https://howtodoinjava.com/jaxb/jaxb-annotations/ or other Jaxb tutorials for other annotations.
Edit:
For login and email, you have to annotate them with #XmlAttribute as well.
` This is my xml code.Iam very new to restservice.
<?xml version="1.0" encoding="UTF-8"?>
<departments>
<deptname name="Research">
<employee>
<eid>r-001</eid>
<ename>Dinesh R</ename>
<age>35</age>
<deptcode>d1</deptcode>
<deptname>Research</deptname>
<salary>20000</salary>
</employee>
</deptname>
<deptname name="Sales">
<employee>
<eid>s-001</eid>
<ename>Kanmani S</ename>
<age>35</age>
<deptcode>d2</deptcode>
<deptname>Sales</deptname>
<salary>30000</salary>
</employee>
</deptname>
</departments>
By using this xml i want to create Restservice.I have tried , i created java classes for that(i don't know that correct or not ).but i am stuck in controller in that area how i will mapping.
Here is a simplest way, in my opinion
1) create a Departments pojo
2) create Department pojo which will be composed (composition) into departments
3) create a regular springboot controller, ensure the controller method produces and consumes application/xml
4) include below dependency in your pom.xml
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
here is my example,
Departments.java
import org.springframework.stereotype.Component;
#Component
public class Departments {
private List<Department> department;
public List<Department> getDepartment() {
return department;
}
public void setDepartment(List<Department> department) {
this.department = department;
}
}
Department.java
import org.springframework.stereotype.Component;
#Component
public class Department {
private String name;
private String id;
private int employeeCount;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getEmployeeCount() {
return employeeCount;
}
public void setEmployeeCount(int employeeCount) {
this.employeeCount = employeeCount;
}
#Override
public String toString() {
return "Department [name=" + name + ", id=" + id + ", employeeCount=" +
employeeCount + "]";
}
public Department() { }
public Department(String name) {
this.name = name;
}
public Department(String name, String id) {
this.name=name;
this.id=id;
}
public Department(String name, String id, int employeeCount) {
this.name=name;
this.id=id;
this.employeeCount = employeeCount;
}
}
SpringBootApplication.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication(scanBasePackages = {"test.controllers","test.main", "test.model"})
public class ServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
}
SpringController
#RestController
public class GreetingController {
#RequestMapping("/hello/{name}")
String hello(#PathVariable String name) {
return "Hello, " + name + "!";
}
#PostMapping(path = "/departments", produces = MediaType.APPLICATION_XML_VALUE, consumes = MediaType.APPLICATION_XML_VALUE)
#ResponseBody
Departments newEmployee(#RequestBody List<Department> departments) {
Departments departmentsObj = new Departments();
for(Department department : departments) {
System.out.println(department);
}
departmentsObj.setDepartment(departments);
return departmentsObj;
}
}
For testing purposes, I used used JAXB to generate an XML from an Object. This work fine. The code is below.
package com.mns.mnsutilities.jaxb.model;
import java.util.List;
import javax.xml.bind.annotation.*;
#XmlRootElement(name="Emp_MNS")
#XmlType(propOrder= {"name", "age", "role", "gender", "addressesList"})
public class Employee {
private int id;
private String gender;
private int age;
private String name;
private String role;
private String password;
private List<Address> addressesList;
public Employee() {}
public Employee(int id, String gender, int age, String name, String role,
String password) {
super();
this.id = id;
this.gender = gender;
this.age = age;
this.name = name;
this.role = role;
this.password = password;
}
public Employee(int id, String gender, int age, String name, String role,
String password, List<Address> addressesList) {
super();
this.id = id;
this.gender = gender;
this.age = age;
this.name = name;
this.role = role;
this.password = password;
this.addressesList = addressesList;
}
#XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement(name = "gen")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// #XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
#XmlElement(nillable=true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
#XmlTransient
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#XmlElement(name = "addresses")
public List<Address> getAddressesList() {
return addressesList;
}
public void setAddressesList(List<Address> addressesList) {
this.addressesList = addressesList;
}
#Override
public String toString() {
return "Employee [id=" + id + ", gender=" + gender + ", age=" + age
+ ", name=" + name + ", role=" + role + ", password="
+ password + ", addressesList=" + addressesList + "]";
}
}
And:
package com.mns.mnsutilities.jaxb.model;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(namespace="")
public class Address {
private String street;
private String city;
private String zipCode;
private String country;
public Address() {}
public Address(String street, String city, String zipCode, String country) {
super();
this.street = street;
this.city = city;
this.zipCode = zipCode;
this.country = country;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Override
public String toString() {
return "Address [street=" + street + ", city=" + city + ", zipCode="
+ zipCode + ", country=" + country + "]";
}
}
My main Class is :
package com.mns.mnsutilities.jaxb.batch;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import com.mns.mnsutilities.jaxb.model.Address;
import com.mns.mnsutilities.jaxb.model.Employee;
public class LaunchAction {
private static final String FILE_NAME = "output/CT3D_XML_SAMPLE_FINAL.xml";
public static void main(String[] args) {
Employee emp = new Employee();
emp.setId(1);
emp.setAge(25);
emp.setName("Yovan");
emp.setGender("Male");
emp.setRole("Developer");
emp.setPassword("sensitive");
List<Address> addressesList = new ArrayList<>();
Address address1 = new Address("Main Road", "Ebene", "11111", "Mauritius");
Address address2 = new Address("Royal Road", "Rose-Hill", "2222", "Mauritius");
addressesList.add(address1);
addressesList.add(address2);
emp.setAddressesList(addressesList);
jaxbObjectToXML(emp);
Employee empFromFile = jaxbXMLToObject();
System.out.println(empFromFile.toString());
}
private static Employee jaxbXMLToObject() {
try {
JAXBContext context = JAXBContext.newInstance(Employee.class);
Unmarshaller un = context.createUnmarshaller();
Employee emp = (Employee) un.unmarshal(new File(FILE_NAME));
return emp;
} catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
private static void jaxbObjectToXML(Employee emp) {
try {
JAXBContext context = JAXBContext.newInstance(Employee.class);
Marshaller m = context.createMarshaller();
//for pretty-print XML in JAXB
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
// Write to System.out for debugging
m.marshal(emp, System.out);
// Write to File
m.marshal(emp, new File(FILE_NAME));
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
The XML output is :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Emp_MNS id="1">
<name xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true">
</name>
<age>25</age>
<role>Developer</role>
<gen>Juggoo</gen>
<addresses>
<city>Ebene</city>
<country>Mauritius</country>
<street>Main Road</street>
<zipCode>11111</zipCode>
</addresses>
<addresses>
<city>Rose-Hill</city>
<country>Mauritius</country>
<street>Royal Road</street>
<zipCode>2222</zipCode>
</addresses>
</Emp_MNS>
What I really would like to have is :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Emp_MNS id="1">
<name xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true">
</name>
<age>25</age>
<role>Developer</role>
<gen>Juggoo</gen>
<addresses>
**<address>**
<city>Ebene</city>
<country>Mauritius</country>
<street>Main Road</street>
<zipCode>11111</zipCode>
**</address>**
**<address>**
<city>Rose-Hill</city>
<country>Mauritius</country>
<street>Royal Road</street>
<zipCode>2222</zipCode>
**</address>**
</addresses>
</Emp_MNS>
Could you please guide me on how to proceed?
You can do the following:
#XmlElementWrapper(name="addresses")
#XmlElement(name="address")
public List<Address> getAddressesList() {
i have the following classes which is marshalled as an XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="100">
<age>21</age>
<hobbies>
<hobby>
<cost>sd</cost>
<name>na</name>
</hobby>
<hobby>
<cost>sd</cost>
<name>nb</name>
</hobby>
</hobbies>
<name>test</name>
</customer>
However, when i tried to unmarshall, I can only create the customer object but not hobby, which returns null
Am i doing something wrong here? The problem seems to be with the XML hierarchy?
package com.mytest.jxb;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
#XmlRootElement(name="customer")
#XmlSeeAlso({Hobby.class})
public class Customer {
String name;
int age;
int id;
#XmlElementRef
private List<Hobby> hobbyList = new ArrayList<Hobby>();
public Customer(){
//hobbyList = new ArrayList<Hobby>();
}
//#XmlElement
public String getName() {
return name;
}
#XmlElement
public void setName(String name) {
this.name = name;
}
//#XmlElement
public int getAge() {
return age;
}
#XmlElement
public void setAge(int age) {
this.age = age;
}
//#XmlAttribute
public int getId() {
return id;
}
#XmlAttribute
public void setId(int id) {
this.id = id;
}
public void addHobby(Hobby h) {
hobbyList.add(h);
}
#XmlElementWrapper(name="hobbies")
#XmlElement(name = "hobby")
public List<Hobby> getHobbies(){
return hobbyList;
}
}
package com.mytest.jxb;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
class Hobby {
private String name;
private String cost;
public Hobby(){
}
public Hobby(String name, String cost){
this.name = name;
this.cost = cost;
}
//#XmlElement
public void setName(){
this.name = name;
}
#XmlElement
public String getName(){
return name;
}
//#XmlElement
public void setCost(){
this.cost = cost;
}
#XmlElement
public String getCost(){
return cost;
}
}
Having addHobby(Hobby h) is not enough for JAXB. Your class should be real POJO and should have void setHobbies(List<Hobby> hobbyList) { this.hobbyList = hobbyList; }. Also I think you can safely remove #XmlElementRef from hobbyList field.
EDIT: I have checked your classes and created the version which works OK:
package test;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
#XmlRootElement(name = "customer")
public class Customer {
String name;
int age;
int id;
private List<Hobby> hobbyList = new ArrayList<Hobby>();
public Customer() {
}
#XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlElement
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void addHobby(Hobby h) {
hobbyList.add(h);
}
#XmlElementWrapper(name = "hobbies")
#XmlElement(name = "hobby")
public List<Hobby> getHobbies() {
return hobbyList;
}
#Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
}
package test;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
#XmlRootElement
class Hobby {
private String name;
private String cost;
public Hobby() {
}
public Hobby(String name, String cost) {
this.name = name;
this.cost = cost;
}
public void setName(String name) {
this.name = name;
}
#XmlElement
public String getName() {
return name;
}
public void setCost(String cost) {
this.cost = cost;
}
#XmlElement
public String getCost() {
return cost;
}
#Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
}