Java Reference
In-Depth Information
The dots represent child elements, as before, and this time the @ symbols imply attributes.
Parsing XML
Dots traverse from parent elements to children, and @ signs represent attribute values.
XML, regular expressions, and the Groovy Truth
Todosomeslightly moreinteresting processing, consider determining thewinningandlos-
ing pitchers. The XML contains that information in a note attribute of the pitcher ele-
ment. I can process that using a regular expression, assuming it exists at all:
def pitchers = boxscore.pitching.pitcher
pitchers.each { p ->
if (p.@note && p.@note =~ /W|L|S/) {
println " ${p.@name} ${p.@note}"
}
}
First I select all the pitcher elements for both teams. Then I want to examine the
pitcher elements to find out who won and lost and if anyone was assigned a save. In the
XML this information is kept in a note annotation in the pitcher element, which may
or may not exist.
In the if statement, therefore, I check to see if a note attribute is present. Here I'm using
the “Groovy Truth,” which means that non-null references evaluate to true. So do non-
empty strings or collections, non-zero numbers, and, of course, the boolean literal true .
If the note element is present, I then use the so-called “slashy” syntax to check to see if
the note matches a regular expression: p.@note =~ /W|L|S/ . If there's a match I print
out the values.
Generating Game Results
Before I show the complete method I need one more section. For the Groovy Baseball ap-
plication I'm not interested in console output. Rather, I want to assemble the game results
into a format that can be processed in the view layer by JavaScript. That means I need to
return an object that can be converted into XML (or JSON).
Search WWH ::




Custom Search