Finding Empty XML Element Attribute With XmlSlurper

Groovy’s XmlSlurper does excelent job parsing XML and it’s quite easy to use once you figure it out. Its groovy syntax covers most parsing needs but in some cases you need to dive into its Java roots… Today I was parsing XHTML trying to find OPTION element with SELECTED attribute, that in some documents has zero-length value:

   <option value="1" selected="">Something</option>

Testing attribute using XmlSlurper syntax @selected didn’t work as expected. However, as XML element is an instance of groovy.util.slurpersupport.NodeChild, you can check if attribnute exists using expression:

   element.attributes().get('selected') != null

Comments