How do I create my own xml data to be used with Restful web service in Java? I did create a string file using StringBuilder but when I tried consuming at the client side there is always a problem extracting the attributes from it there is always an error.

Listed below is my code;

Employee emp0 = new Employee("David", "Finance");
Employee emp1 = new Employee("Smith", "HealthCare");
Employee emp2 = new Employee("Adam", "Information technology");
Employee emp3 = new Employee("Stephan", "Life Sciences");

map.put("00345", emp0);
map.put("00346", emp1);
map.put("00347", emp2);
map.put("00348", emp3);

@GET
@Path("{id}")
@Produces({"application/xml"})
public String find(@PathParam("id") String id) {

    Employee emp = (Employee) map.get(id);
    if (emp != null) {
        StringBuilder br = new StringBuilder();
        br.append("<?xml version='1.0' encoding='UTF-8'?>").append(nl);
        br.append("<Employee>").append(nl);
        br.append("<Emp-ID>").append(id).append(" </Emp-ID >").append(nl);
        br.append("<Name>").append(emp.getName()).append(" </Name>").append(nl);
        br.append("<dept>").append(emp.getDept()).append(" </Department>").append(nl);
        br.append("</Employee>");
        return br.toString();
    } else {
        return "Unknown id";
    }
}

I have a POJO by the name of Employee with Name and Department as attributes as well. Thanks.

share|improve this question

2 Answers

up vote 0 down vote accepted

If you add an @XmlRootElement(name="Employee") annotation on your Employee class then you could do the following:

@GET
@Path("{id}")
@Produces({"application/xml"})
public Employee find(@PathParam("id") String id) {

    return (Employee) map.get(id);

}

Then the @XmlElement annotation can be used to override the element names. You can also leverage a JAX-RS Response object to return a status code rather than a String error message.

For More Information

share|improve this answer

i would suggest you use JAXB annotations on your Employee class instead of this stringbuilder exercise.
this link should help you get started
and this link should answer any further questions

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.