[groovy-user] GPath - find all elements with a given attribute

304 views
Skip to first unread message

John Moore

unread,
May 2, 2012, 9:33:54 AM5/2/12
to us...@groovy.codehaus.org
I'm tring to use XmlSlurper to process some XML, replacing all 'id'
attributes with a prefixed value. I must have misunderstood something about
GPath, because I'm ending up processing more elements than I want. Basically
my XML is like this:



My code is below. I am HOPING to process all nodes, at any level, contained
within the <form> element (so, abc, def, etc). What I'm finding, though, is
that the <form> element itself is being processed as well. How can I avoid
this?



--
View this message in context: http://groovy.329449.n5.nabble.com/GPath-find-all-elements-with-a-given-attribute-tp5680541.html
Sent from the groovy - user mailing list archive at Nabble.com.

---------------------------------------------------------------------
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email


Paul King

unread,
May 2, 2012, 4:58:55 PM5/2/12
to us...@groovy.codehaus.org

Your code didn't show up on the mailing list but is on nabble.
Perhaps next time a direct email to the list might be better - don't
know why it had problems though. Anyway, try:

div.form.'*'.'**'

Cheers, Paul.

John Moore

unread,
May 3, 2012, 7:28:42 AM5/3/12
to us...@groovy.codehaus.org
Great, that worked, thanks. Could you please explain why it worked, and why
the previous version didn't? I'm keen to understand this area a little
better.

I've been having problems with the Groovy mailing list for some time, don't
know why. I think I may have to unsubscribe and resubscribe under a
different account.

--
View this message in context: http://groovy.329449.n5.nabble.com/GPath-find-all-elements-with-a-given-attribute-tp5680541p5682922.html

Tim Yates

unread,
May 3, 2012, 8:00:37 AM5/3/12
to us...@groovy.codehaus.org
The depth first iterator also iterates over the node itself (as the first element of the iteration)

Using Paul's solution, you only perform a depth first iteration over the children of this node.  It is the same as doing:

div.form.children().'**'.grep { println it ; it.@id.text()}

So does not pass the form itself

Hope this helps!

Tim

John Moore

unread,
May 3, 2012, 8:26:52 AM5/3/12
to us...@groovy.codehaus.org
Thanks for the explanation. I actually tried out using div.form.children()...
yesterday, figuring that that must be what the issue was, but got an error
suggesting it wasn't valid. I just tried again now and it's fine, so I
reckon there must have been some other syntax error which threw me off the
scent.

--
View this message in context: http://groovy.329449.n5.nabble.com/GPath-find-all-elements-with-a-given-attribute-tp5680541p5683030.html
Reply all
Reply to author
Forward
0 new messages