Power Groovy DSL Features
[ 158 ]
Using GPath to navigate a node tree
We've used GPath in the preceding code to access the node structure created from
our markup. To make sense of how the GPath syntax works, we must visualize it as
a tree structure where customers is the root node. Node attributes are accessible as
map entries, so element.'@attribute' is used to access the attribute values:
assert customers.customer[0].'@id' == 1001
assert customers.customer[1].'@id' == 1002
The following is the root customers node. Each node can have 1 to n leaf nodes, so
customer is always returned as a list object even if only one item is contained in the
list. We access individual elements by using array syntax (customer[1]) but any list
method can be used. The following snippet will list the first names of all customers
in the tree:
customers.customer.each {
println it.name[0].'@firstName'
}
As we index deeper into the tree, we still need to use array syntax to access the lower
nodes, even if the elements at these levels are singletons. Here we assert that Fred
and Wilma live at the same address:
assert customers.customer[0].address[0].'@street'
== customers.customer[1].address[0].'@street'
Finally, we can use a more complex GPath query to assert that all the Rubbles live
at 2 Rock Road. This is quite a complex query, so we will decompose it, as shown
in the following snippet. First, we use grep on the root customers node to produce
a tree of all customers whose surname is Rubble. This tree should have two nodes:
one for Barney and one for Betty:
def rubbles = customers.grep{ it.name.any{it.'@surname' == "Rubble"}}
Now we can assert that every Rubble lives at 2 Rock Road:
assert rubbles.address.every{ it.'@street'[0] == "2 Rock Road"}
SwingBuilder
Most Java developers I know hate Swing UIs with a passion. The reason people
hate Swing is because of the APIs. Let's face it, Swing UIs are a chore to build and
maintain, due to the unwieldy nature of the Swing APIs.
http://www.ebook3000.com