Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Response XML with JAXB

Tags:

java

xml

jaxb

I want to read a response from a non-wsdl web service call using JAXB. I am sending a POST request using HttpURLConnection, and getting a response. My question is do I make an xml doc from the response stream, then use jaxb to make the java objects? Or, is it possible to use use jaxb on the fly with the response stream? This will be a web application, and I will not be able to store a generated xml doc anywhere, so if i need to make an xml doc, how do i store it for jaxb to use, if I cannot do the jaxb on the fly?

like image 830
bmw0128 Avatar asked Dec 16 '10 20:12

bmw0128


People also ask

Is JAXB XML parser?

JAXB — Java Architecture for XML Binding — is used to convert objects from/to XML. JAXB offers a fast and suitable way to marshal (write) Java objects into XML and unmarshal (read) XML into Java objects. It supports Java annotations to map XML elements to Java attributes.

How does JAXB read XML?

To read XML, first get the JAXBContext . It is entry point to the JAXB API and provides methods to unmarshal, marshal and validate operations. Now get the Unmarshaller instance from JAXBContext . It's unmarshal() method unmarshal XML data from the specified XML and return the resulting content tree.

What is the best way to parse XML in Java?

DOM Parser is the easiest java xml parser to learn. DOM parser loads the XML file into memory and we can traverse it node by node to parse the XML. DOM Parser is good for small files but when file size increases it performs slow and consumes more memory.


2 Answers

Here is an example:

String uri =
    "http://localhost:8080/CustomerService/rest/customers/1";
URL url = new URL(uri);
HttpURLConnection connection =
    (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");

JAXBContext jc = JAXBContext.newInstance(Customer.class);
InputStream xml = connection.getInputStream();
Customer customer =
    (Customer) jc.createUnmarshaller().unmarshal(xml);

connection.disconnect();

For more information see:

  • http://bdoughan.blogspot.com/2010/08/creating-restful-web-service-part-55.html
like image 123
bdoughan Avatar answered Oct 09 '22 14:10

bdoughan


The Unmarshaller.unmarshal can take an InputStream, which would eliminated the need to parse it to an XML doc.

like image 21
sblundy Avatar answered Oct 09 '22 14:10

sblundy