Sharique
Sharique

Reputation: 859

Map XML(of same tag name) to Java Object

I got a requirement that I have to map my xml to java object without parsing it, but the problem is like that in xml tag names would be same, for example,

 <response>
    <employee>
    <name>Sharique</name>
    <name>24</name>
    <name>India</name>
    </employee>
    </response>

and class would be like this

public class Employee{
private String empName;
private int age;
private String country;

//getters and setters
}

Please help!! If it can be done using spring than that would be very nice

Upvotes: 2

Views: 1276

Answers (3)

bdoughan
bdoughan

Reputation: 149017

If you leverage EclipseLink MOXy as your JAXB (JSR-222) provider then you can use our @XmlPath extension for this use case.

@XmlAccessorType(XmlAccessType.FIELD)
public class Employee{
    @XmlPath("name[1]/text()")
    private String 

    @XmlPath("name[2]/text()")
    private int age;

    @XmlPath("name[3]/text()")
    private String country;

    //getters and setters
}

For More Information

I have written more about the @XmlPath extension on my blog:

Upvotes: 1

Cfx
Cfx

Reputation: 2312

You really got some weird XML there. I thing data binding will not help in this case, but you can do it with data projection. (Disclosure: I'm affilited with that project)

public class ParseResponse {

public interface Employee {
    @XBRead("./name[1]")
    String getName();

    @XBRead("./name[2]")
    int getAge();

    @XBRead("./name[3]")
    String getCountry();
}


public static void main(String[] args) {
    List<Employee> employees = new XBProjector().io().url("res://response.xml").evalXPath("//employee").asListOf(Employee.class);
    for (Employee employee:employees) {
        System.out.println(employee.getName());
        System.out.println(employee.getAge());
        System.out.println(employee.getCountry());
    }
    }
}

this program prints out

Sharique
24
India

if you fix the XML closing tags.

Upvotes: 0

Kalaiarasan Manimaran
Kalaiarasan Manimaran

Reputation: 1658

Not required, As per javax.xml.bind.annotation you can do like below,

@XmlElement(name="name")
    private String empName;

So now the empName in your java class will be mapped to name attribute in your XML.

and your XML should not have 'name' as name for all attributes. it cannot differentiate, so you need to use different tags in your XML for other elements like age and so on ans map accordingly as i stated above in your POJO.

Upvotes: 0

Related Questions