Sandeep is a ITA at Tata Consultancy Services. He also is the author of java blog. Sandeep has posted 24 posts at DZone. You can read more from them at their website. View Full User Profile

Specifying XML Tag Attributes with CXF Rest Web Services

05.20.2011
| 4365 views |
  • submit to reddit

CXF comes with a reference implementation of JSR-311which is the specification for Restful web services also known as JAX-RS.We can generate XML output using Rest web services using CXF framework. Please note that CXF is a framework which is being maintained by Apache foundation.

In order to have attributes in the various XML tags being generated by using CXF, one has to use the @XmlAttribute annotation to declare attributes for a particular xml element. Usually each unique tag in XML output corresponds to a single class in a CXF REST web service.

For using the @XmlAttribute annotation, one needs to import the class  javax.xml.bind.annotation.XmlAttribute

It is worth noting that the XmlAttribute class is available to you if you are using JDK 6. If you are using anything older  than JDK 6 then you can download the JSR-311 reference implementation jar from the following location:

http://download.java.net/maven/2/javax/ws/rs/jsr311-api/0.9/

Also the @XmlAttribute annotation can be used with a field or a javabean getter property method but not with both for the same field. What we mean here is that if you have a field named "empid" and corresponding getters and setters for empid as getEmpid and setEmpid then you should either use the attribute annotation with the string variable or the getter method but not both. If used with both, an exception about duplicate attributes will thrown.

Please not that if you make a member variable as the attribute in the XML output of CXF Restful web services then that member variable will not become a child of the tag being represented by the current class.

Here is the javadoc for @XmlAttribute annotation:http://download.oracle.com/javaee/5/api/javax/xml/bind/annotation/XmlAttribute.html

From http://extreme-java.blogspot.com/2011/05/specifying-xml-tag-attributes-with-cxf.html

Published at DZone with permission of its author, Sandeep Bhandari.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: