[groovy-user] XmlSlurper: cannot get parent attributes from node

127 views
Skip to first unread message

spex66

unread,
Jun 7, 2011, 8:57:33 AM6/7/11
to us...@groovy.codehaus.org
Hi there,

I get crazy.. really.
GPathResult navigation and magic will not work out how (intuitive) expected.
I have tried a lot of variants (by try and error).
Expected is to get *only* the attributes of the *direct* parent node.

parent() is singular, isn't it.
The different result classes "GPathResult", "NodeChildren", "NodeChild",
"Node" for different things, will not make it easier.

It looks as the easiest task, that exists...
How should I reach my goal?
Thank you all for your feedback.
regards
(=PA=)

a = """

<z id="z1" />


<z id="z2" />


<z id="z3" />

"""
x = new XmlSlurper().parseText(a)
x.b.z.each{ node ->
println node.@id
println ' ' + node."..".@name
println ' ' + node."..".size()
// println ' ' + node."..".attributes() <- traceback
println ' ' + node.".."*.attributes()
}


Output:

z1
b1b2b3
3
[[name:b1], [name:b2], [name:b3]]
z2
b1b2b3
3
[[name:b1], [name:b2], [name:b3]]
z3
b1b2b3
3
[[name:b1], [name:b2], [name:b3]]


-----
(=PA=)
.oO Just started Groovy after 12 yrs of Python Oo.
--
View this message in context: http://groovy.329449.n5.nabble.com/XmlSlurper-cannot-get-parent-attributes-from-node-tp4461683p4461683.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,
Jun 7, 2011, 9:14:06 AM6/7/11
to us...@groovy.codehaus.org

If you want navigation to follow a DOM-like conceptual model
I suggest swapping in XmlParser for XmlSlurper. The slurper
has a slightly different conceptual model which normally doesn't
surface but does with '..'. Here's an example:

def x = new XmlParser().parseText(a)


x.b.z.each{ node ->
println node.@id
println ' ' + node."..".@name
}

For XmlSlurper, '..' means undo one level of expression rather
than jump up a level in the "DOM" tree.

Cheers,
Paul.

spex66

unread,
Jun 7, 2011, 9:26:51 AM6/7/11
to us...@groovy.codehaus.org
Hi Paul,

thank you for pointing that out.
But this is "so not expected" and not documented in all the starter guides
as well.
Neither the code gave me that clue. Amazing.

I like XmlSlurper haptic and don't want to go to *raw* XmlParser back again
:-)

thank you
(=PA=)

My Solution:
I decided to switch to nested loops on that level where I need access to
direct parents:

x = new XmlSlurper().parseText(a)
x.b.each{ bnode ->
bnode.z.each{ node ->
println node.@id
println ' ' + bnode.attributes()
}
}

Output:

z1
[name:b1]
z2
[name:b2]
z3
[name:b3]


-----
(=PA=)
.oO Started with Groovy1.8 just after 12 yrs of Python Oo.
--
View this message in context: http://groovy.329449.n5.nabble.com/XmlSlurper-cannot-get-parent-attributes-from-node-tp4461683p4461774.html

Reply all
Reply to author
Forward
0 new messages