1

I have an XML as follows ...

<employeeId>323</employeeId>
<name>Samuel DCosta</name>
<department>
    <departmentId>2</departmentId>
    <name>Accounts</name>
</department>
<salary>11290</salary>

I want to map these values to the Java Beans that I have .... the keys in the XML match with the name of the members in the beans ..... someone tell me if there is a simple way to do this in Java please .... tools or components welcome ...

Department ....

import java.io.Serializable;

public class Department implements Serializable
{
private Long departmentId;

private String name;

@Override
public String toString()
{
    return "Department [departmentId=" + departmentId + ", name=" + name + "]";
}

public Long getDepartmentId()
{
    return departmentId;
}

public void setDepartmentId(Long departmentId)
{
    this.departmentId = departmentId;
}

public String getName()
{
    return name;
}

public void setName(String name)
{
    this.name = name;
}
}

Employee .....

import java.io.Serializable;

public class Employee implements Serializable
{
private Long employeeId;

private String name;

private Department department;

private Integer salary;

@Override
public String toString()
{
    return "Employee [employeeId=" + employeeId + ", name=" + name + ", department=" + department + ", salary="
            + salary + "]";
}

public Long getEmployeeId()
{
    return employeeId;
}

public void setEmployeeId(Long employeeId)
{
    this.employeeId = employeeId;
}

public String getName()
{
    return name;
}

public void setName(String name)
{
    this.name = name;
}

public Department getDepartment()
{
    return department;
}

public void setDepartment(Department department)
{
    this.department = department;
}

public Integer getSalary()
{
    return salary;
}

public void setSalary(Integer salary)
{
    this.salary = salary;
}
}
2

4 Answers 4

4

You can use JAX-B

Java Architecture for XML Binding (JAXB) provides a fast and convenient way to bind XML schemas and Java representations, making it easy for Java developers to incorporate XML data and processing functions in Java applications. As part of this process, JAXB provides methods for unmarshalling (reading) XML instance documents into Java content trees, and then marshalling (writing) Java content trees back into XML instance documents. JAXB also provides a way to generate XML schema from Java objects

Sign up to request clarification or add additional context in comments.

Comments

3

First, add JAXB annotation to your bean class:

    @XmlRootElement
    public class Employee {
    private Long employeeId;
    private String name;
    private Department department;

    private Integer salary;
    //getter and setter omitted here
   }

@XmlRootElement
public class Department {
    private Long departmentId;
    private String name;
     //getter and setter omitted here
}

This the 'employee.xml' file I used for testing:

<employee>
    <employeeId>323</employeeId>
    <name>Samuel DCosta</name>
    <department>
        <departmentId>2</departmentId>
        <name>Accounts</name>
    </department>
    <salary>11290</salary>
</employee>

Then you can read a XML file like this

public class EmployeeReader {
public static <T> T fromXML(Reader reader,Class<T> type) throws JAXBException {
    JAXBContext context=JAXBContext.newInstance(type);
    Unmarshaller unmarshaller=context.createUnmarshaller();
    return (T)unmarshaller.unmarshal(reader);
}

    public static void main(String[] args)
    {
        Reader reader=null;
        try
        {
            reader=new FileReader("employee.xml");
            Employee employee= EmployeeReader.fromXML(reader,Employee.class);
            System.out.println(employee.getName());
            System.out.println(employee.getDepartment().getName());
        }catch (Exception e)
        {
            e.printStackTrace();
        }finally {
        IOUtils.closeQuietly(reader);
    }
    }
}

2 Comments

The fromXML method will return only the Employee bean. Cant it be generalized so as to work for any kind of Java Bean?
@Brian James, Yes, we can use generic here
0

I used your original XML and the 2 Java Beans- Employee and Department in my test code

import java.util.ArrayList;
import java.util.List;

import cjm.component.cb.object.ToObject;

public class EmployeeConversion
{
public static void main(String[] args)
{
    try
    {
        String xml = "<employeeId>323</employeeId><name>Samuel DCosta</name><department><departmentId>2</departmentId><name>Accounts</name></department><salary>11290</salary>";

        List<Object> objectList = new ArrayList<Object>();

        objectList.add(new Employee());
        objectList.add(new Department());         // adding all the nested objects within the Employee bean into this list

        Employee employee = (Employee) new ToObject().convertToObject(xml, new Employee(), objectList); // this will carry out the mapping to the bean

        System.out.println(employee);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
}

Output

-------- XML Detected -------- 
-------- XML Detected -------- 
-------- Map created Successfully -------- 
-------- Object created Successfully -------- 
Employee [employeeId=323, name=Samuel DCosta, department=Department [departmentId=2, name=Accounts], salary=11290]

You will need the Conversion Box (go for v1.1) http://capsulesforthejavamind.blogspot.in/2015/01/conversion-box.html

Ping me with the results!!! :)

Comments

0

You can generate an xsd file for the xml you provided and then use JAXB for auto generating java classes corresponding to the schema using eclipse. For Auto generating the java classes, you can take help of below link: How can I get the "Eclipse >Generate>Jaxb classes" option back?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.