Java Reference
In-Depth Information
if (v.length() > 0) {
uniqueAuthors.add(v);
}
}
}
}
The reader's getText method gives the event value, and the getAttributeValue method is
used with an integer indicating the index of the attribute you want a value for.
Running the program produces the following results:
AttribName sku=123_xaa
AttribName sku=988_yty
AttribName sku=434_asd
AttribName sku=876_pep
Unique Authors=[George Orwell, Maurice Naftalin, Phillip Wadler,
William Shakespeare]
In this example, you are interested in authors (which are their own element) and SKU values
(which are attributes of the book element). You save the name of the current node for each
iteration of the loop so that you can match it in your two processing methods.
NOTE
Normally, you'll just want to use the StAX implementation that comes with Java SE 6. But it's
worth noting that Sun has an implementation of StAX available as a separate download from ht-
tps://sjsxp.dev.java.net/ . This implementation is built on Xerces 2, and is very lazy (a good thing for
parsers!). There are other StAX implementations available as well, such as those from Oracle.
Using the StAX iterator model
The iterator API is the more flexible and easily extensible of the two models.
Let's parse the same Catalog.xmldocument just defined with the other StAX model, the iter-
ator. This is shown in Example 3-2 .
Example3-2.Reading XML with StAX iterator
public class StaxIterator {
public void find() {
XMLInputFactory xif = XMLInputFactory.newInstance();
//forward-only, most efficient way to read
XMLEventReader reader = null;
//get ahold of the file
Search WWH ::




Custom Search