I am new to JAXB and would like to know if there is a way by which I can unmarshall an XML to my response object but using xpath expressions. The issue is that I am calling a third party webservice and the response which I receive has a lot of details. I do not wish to map all the details in the XML to my response object. I just wish to map few details from the xml using which I can get using specific XPath expressions and map those to my response object. Is there an annotation which can help me achieve this?
For example consider the following response
<root>
<record>
<id>1</id>
<name>Ian</name>
<AddressDetails>
<street> M G Road </street>
</AddressDetails>
</record>
</root>
I am only intrested in retrieving the street name so I want to use xpath expression to get value of street using 'root/record/AddressDetails/street' and map it to my response object
public class Response{
// How do i map this in jaxb, I do not wish to map record,id or name elements
String street;
//getter and setters
....
}
Thanks
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JST-222) expert group.
You could use MOXy's
@XmlPath
extension for this use case.Response
jaxb.properties
To use MOXy as your JAXB provider you need to include a file called
jaxb.properties
in the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html)Demo
Output
For More Information
If all you want is the street name, just use an XPath expression to get it as a string, and forget about JAXB - the complex JAXB machinery is not adding any value.
If you want to map to the middle of an XML document you could do the following:
Demo Code
You could use a StAX parser to advance to the part of the document you wish to unmarshal, and then unmarshal the
XMLStreamReader
from there,.Response
The mappings on the domain object are made relative to the fragment of the XML document you are mapping to.
Output
For More Information