Java Reference
In-Depth Information
We now modify our example and make it use a mix of DOM parsing and JAXB unmarshalling. Again, we only
change the getObservableList() method. The modified implementation is shown in Listing 11-9.
Listing 11-9. Combining XML Parsing and JAXB
ObservableList<Question> getObservableList() throws IOException, ParserConfigurationException,
SAXException {
ObservableList<Question> answer = FXCollections.observableArrayList();
InputStream inputStream = this.getClass().getResourceAsStream("/stackoverflow.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(inputStream);
NodeList questionNodes = doc.getElementsByTagName("item");
int count = questionNodes.getLength();
for (int i = 0; i < count; i++) {
Element questionNode = (Element) questionNodes.item(i);
DOMSource source = new DOMSource(questionNode);
final Question question = (Question) JAXB.unmarshal(source, Question.class);
answer.add(question);
}
return answer;
}
The only difference between this approach and the approach used in Listing 11-8 is the parsing of the individual
questions. Instead of using DOM parsing for obtaining the specific fields of the individual questions, we use the
unmarshal method in JAXB. The JAXB specifications allow for lots of flexibility and configuration, and the JAXB.
unmarshal method is only a convenience method. However, in many cases, this method is sufficient. The JAXB.
unmarshal method takes two parameters: the input source and the class that is the result of the conversion.
We want to convert the XML source into instances of our Question class, but how does the JAXB framework know
how to map the fields? In many cases, the mapping is straightforward and does not require changes to existing code,
but in other cases, the mapping is a bit more complex. Good enough, a whole package with annotations exists that we
can use to help JAXB determine the conversion between XML and the Java Object.
To make the code in Listing 11-9 work, we made some minor modifications to the Question class. The new code
for the Question class is shown in Listing 11-10.
Listing 11-10. Question Class with JAXB Annotations
package projavafx;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@XmlAccessorType(XmlAccessType.FIELD)
public class Question {
private String owner;
@XmlElement(name = "title")
private String question;
@XmlElement(name = "creation_date")
private long timestamp;
 
Search WWH ::




Custom Search