Java Reference
In-Depth Information
Figure 11-6.
The result of the question application using XML response
The code in Listing 11-8 shows some similarities to the code in Listing 11-7. In both cases, we process data
available in a text format (JSON or XML) and convert the data into Question instances. In Listing 11-8, the DOM
approach is used to inspect the received response.
An
org.w3c.dom.Document
instance is obtained using the following code.
InputStream inputStream = this.getClass().getResourceAsStream("/stackoverflow.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(inputStream);
In this case, we create a
Document
based on an
InputStream
. The
InputStream
is obtained from the artificially
created file. We can also create an
InputStream
from a
URLConnection
, and pass this
InputStream
to the
db.parse()
method. Even easier, the
DocumentBuilder.parse
method also accepts a
String
parameter that contains the URL of a
(REST) endpoint.
This shows that although we are using a static file containing questions in this case, we can easily use the same
code when using a real REST endpoint.
The resulting
Document
can now be queried. From the XML response shown in Listing 11-6, we learn that the
individual questions are enclosed in XML Elements named “item”. We use the following to obtain a list of those XML
Elements.
NodeList questionNodes = doc.getElementsByTagName("item");
We then iterate over this list, and obtain the question-specific fields by inspecting the
childNodes
in the respective
XML Elements. Finally, we add the resulting question to the
ObservableList
of
Question
objects named answer.
This approach is rather simple, but we still have to do some manual XML parsing. Although this allows for
flexibility, parsing becomes harder and more error prone with increasing complexity of the data structure.
Fortunately, the Java Standard Edition APIs contain tools for converting XML directly into Java Objects. The
specification for these APIs is defined by the JAXB standard, and is available in the
javax.xml.bind
package. The
process of converting XML data into Java Objects is called unmarshalling.
Search WWH ::
Custom Search