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.

2 Answers 2

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

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

Comments

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

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.