Java Reference
In-Depth Information
We added three annotations to the original Question class. First, we annotated the class itself with
@XmlAccessorType(XmlAccessType.FIELD)
This annotation tells the JAXB framework to map XML data on the fields of this class, as opposed to on the
JavaBean properties (getter/setter methods) of this class. The second and third annotations are added to the question
field and the timeStamp field:
@XmlElement(name = "title")
private String question;
@XmlElement(name = "creation_date")
private long timestamp;
This indicates that the question field corresponds to an XML element named “title” and that the timestamp field
corresponds to an XML element named “creation_date.” Indeed, if we look at Listing 11-6, it shows that the question is
in an element with the name “title” and that the timestamp is in an element with the name “creation_date.” We have to
instruct the JAXB runtime to map this element with our timestamp field, and this is what we do with the @XmlElement
annotation.
Using the JAXB annotations made it easy to convert the XML question elements into individual Question
instances, but we still had some manual XML processing in our main class. However, we can completely remove the
manual XMLParsing and convert the whole XML response into a Java Object. Doing so, the getObservableList()
method becomes very simple, as shown in Listing 11-11.
Listing 11-11. Parsing Incoming XML Data Using JAXB
ObservableList<Question> getObservableList() {
InputStream inputStream = this.getClass().getResourceAsStream("/stackoverflow.xml");
QuestionResponse response = JAXB.unmarshal(inputStream, QuestionResponse.class);
return FXCollections.observableArrayList(response.getItem());
}
In this example, we use JAXB to convert the XML response into an instance of QuestionResponse , and the
questions are then obtained via this QuestionResponse instance. Note that we convert the questions from a regular
List object into an ObservableList object, as required by the method signature. We later show an example where we
don't have to do that additional conversion.
The QuestionResponse class has two goals: map the XML response onto a Java Object and make the question
items available as a List of Question instances. This is achieved by the code in Listing 11-12.
Listing 11-12. QuestionResponse Class, Enabling Conversion Between XML Response and Java Objects
package projavafx;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="items")
@XmlAccessorType(XmlAccessType.FIELD)
public class QuestionResponse {
private List<Question> item;
 
Search WWH ::




Custom Search