Tuesday, December 1, 2009

Groovy: Retrieving XML Element Attributes in a Map

The Groovy script below is a little test I came up to help me remember how to grab element attributes from an XML document. In the example message, I want the attributes from the request element in a Map:
  def message = """<message>
<request file="/home/prystasj/file.txt" type="txt" />
<message>"""

def xml = new XmlParser().parseText(message)
def attrs = xml.request[0].attributes()

println "Class: ${attrs.getClass().getName()}"
println "Size: ${attrs.size()}"
println "Attributes: $attrs"
println "File: ${attrs.file}"
println "Type: ${attrs.type}"

The key that tripped me up was that I needed to grab the first request element (indexed at 0) in the assignment to attrs.

The output from the script:

  Class: java.util.LinkedHashMap
Size: 2
Attributes: [file:/home/prystasj/file.txt, type:txt]
File: /home/prystasj/file.txt
Type: txt

No comments:

Post a Comment