Enterprise J2ME Developing Mobile Java Applications [Electronic resources]

Michael Juntao Yuan

نسخه متنی -صفحه : 204/ 142
نمايش فراداده

15.6 Amazon Services via kDOM

Using the kDOM document model, parsing is very simple. Just a few lines of code builds the kDOM tree in a Document type object doc from the input XML stream.

InputStreamReader reader = new InputStreamReader(is);
KXmlParser parser = new KXmlParser();
parser.setInput(reader);
Document doc = new Document ();
doc.parse (parser);

The rest of the methods, getBooksViaDOM() (Listing 15.6) and getBookDetailsViaDOM() (Listing 15.7), in the AmazonLite class demonstrate how to traverse the tree to retrieve useful information. All ignorable white spaces are built into Text nodes by default. We have to be careful not to mistake them with real Element nodes. Since the tree object is already in memory, you can access any random node at anytime. You can even change the content of any node and have kDOM write out the new tree to an I/O stream.

Listing 15.6. The AmazonLite.getBooksViaDOM() method
Vector getBooksViaDOM (InputStream is) throws Exception {
Vector books = new Vector ();
InputStreamReader reader = new InputStreamReader(is);
KXmlParser parser = new KXmlParser();
parser.setInput(reader);
Document doc = new Document ();
doc.parse (parser);
// Use the following code to write
// in memory doc object to a stream
// KXmlSerializer serializer = new KXmlSerializer ();
// serializer.setOutput (System.out, null);
// doc.write (serializer);
// serializer.flush ();
// The <ProductInfo> element
Element prods = doc.getRootElement();
int numOfEntries = prods.getChildCount ();
for (int i = 0; i < numOfEntries; i++) {
if ( prods.isText(i) ) {
// Text here are all insignificant white spaces.
// We are only interested in children elements
} else {
// Not text, must be a <Details> element
Element e = prods.getElement (i);
BookDetails bd = getBookDetailsViaDOM( e );
books.addElement( bd );
}
}
return books;
}
Listing 15.7. The AmazonLite.getBooDetailsViaDOM() method
BookDetails getBookDetailsViaDOM (Element e) throws Exception {
BookDetails bd = new BookDetails ();
// get attribute value from the <Details> start tag
bd.url = e.getAttributeValue(null, "url");
int numOfChildren = e.getChildCount ();
for (int i = 0; i < numOfChildren; i++) {
if ( e.isText(i) ) {
// Ignore
} else {
Element c = e.getElement(i);
String tagname = c.getName();
if ( tagname.equals("ProductName") ) {
// First child is a text node
bd.title = c.getText(0).trim();
}
if ( tagname.equals("Authors") ) {
// Goes down the tree: The second child
// is the first <Author> element. Get the
// first child of that element.
bd.firstAuthor =
c.getElement(1).getText(0).trim();
}
if ( tagname.equals("OurPrice") ) {
// First child is a text node
bd.newPrice = c.getText(0).trim();
}
if ( tagname.equals("UsedPrice") ) {
// First child is a text node
bd.usedPrice = c.getText(0).trim();
}
}
}
return bd;
}