Java Reference
In-Depth Information
Many APIs in Java are designed around a set of interfaces, with the assumption that there
will be many different alternative implementations. In the Java API for XML Processing
(JAXP) world there are many parsers available, so the API is dominated by interfaces. Of
course, you can't instantiate an interface, so using the API comes down to factories and
factory methods.
To parse the XML file using a simple DOM parser, therefore, I first need to acquire the rel-
evantfactory,usingits
newInstance
method.ThenIusethefactorymethod
newDocu-
mentBuilder
, which is admittedly a really good name for a factory method. Parsing the
file is then done through the
parse
method, as expected. Inside the DOM parser the tree
is constructed using, interestingly enough, a SAX parser, which is why I need to prepare
for SAX exceptions.
Assuming I get that far, the result at that point is a reference to the DOM tree. Finding my
answerbytraversingthetreeisquitefranklyoutofthequestion.Traversalsarehighlysens-
itive to the presence of white-space nodes, and the available methods (
getFirstChild
,
getNextSibling
, and the like) aren't really a direct method to my answer. If whoever
put together the XML file had been kind enough to assign each element an ID I could
have used the great
getElementByID
method to extract the node I need, but no such
luck there. Instead I'm reduced to collecting the relevant nodes using
getElement-
sByTagName
, which doesn't return something from the
Collections
framework as
you might expect, but a
NodeList
instead. The
NodeList
class has an
item
method
that takes an integer representing the zero-based index of the node I want, and at long last
I have my title node.
Thenthere'sthefinalindignity,whichisthatthevalueofanodeisnotthecharacter content
I want. No, I have to retrieve the first text child of the node, and only then can I get the
value, which returns the text I needed.
XML and Groovy
I was once teaching a class about Java and XML, and one of the exercises was to extract a
nested value. After taking the students through the awkward, ugly, Java solution, a woman
in the back raised her hand.