2

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.

A--C
  • 36,351
  • 10
  • 106
  • 92
Ayodeji
  • 579
  • 2
  • 8
  • 25

2 Answers2

1

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

Community
  • 1
  • 1
austin
  • 1,171
  • 1
  • 13
  • 32
0

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

bdoughan
  • 147,609
  • 23
  • 300
  • 400