|
|||||||||
|
Digester in the Real World
Although Digester is a straightforward solution, things are not always so ideal in the real world. For example, say you have to parse XML whose elements keep changing based on the input. You typically find such request/response streams in the search world. If you search for a book, you get content that contains data to be populated in the Book object. Searching for a magazine returns content that contains data to be populated in the Magazine object. In such a situation, you end up writing custom Rules.
Listing 5 shows the response from a book search. The boldface lines show the dynamic section of the response.
Listing 5. BookResponse.xml
Listing 6 shows the response from a magazine search. Again, the boldface lines show the dynamic section of the response.
Listing 6. MagazineResponse.xml
You can use the same Digester class you used earlier (DigesterExample) with a little modification to parse XML whose elements continually change this way. Just add the two new methods shown in Listing 7 to the Response class.
Listing 7. Content Related Methods
Now, you need to create a custom Rule that gets triggered whenever Digester encounters the content element. Listing 8 demonstrates how to use a custom Rule. The boldface lines are the extra code that is required.
Listing 8. DigesterExample Class Using a Custom Rule
Two arguments are passed to the program, and the Classes are passed through the command line. The first argument is "contentClass", which is the container for the data in the content elements (boldfaced text in Listings 5 and 6). So, for a Book content item, you need a Book.class. The second argument is the class that is responsible for populating the Book.class. Listing 9 shows the code for a custom Rule. The boldfaced text, getDigester.peek(), returns a reference to the object on the stack. In this example, it would be the type of content object based on the search request.
Listing 9. CustomRule Class
Listing 10 shows the BookBuilder class. The boldfaced text is a reference to the Book object.
Listing 10. BookBuilder Class
Since you extended the Rules, you have to tell Digester to use the ExtendedBaseRules class, which allows more kinds of matching patterns. The methods exposed when you extend the Rule object are add, begin, end, finish, and body. Just like that, you've seen how the Digester package offers simplicity in parsing XML. You can use it with a straightforward mapping, as well as more complex XML schemas, with some simple variations.
|
|||||||||
|
Srinivas C. Nallapati is a developer at WW Grainger, Inc. He is a Sun-certified Java programmer.
| |||||||||
|