1

How can I find an attribute name in XML structure by attribute value using Groovy XmlSlurper/XmlParser. Let's say we have XML:

<root>
    <item id="Correction">
        <desc value_err="Error_3"></desc>
    </item>
    <item id_err="Error_2">
        <desc />
    </item>
</root>

I need to find attribute name by value (Initial task: find list of nodes where attribute value like 'Error_'). e.g "Error_2" -> id_err and "Error_3" -> value_err

The only solution I found iteration through all Node attributes map. Is there any GPath for it?

Small remark: we're not able to change structure of XML. This is external exception API.

Alex
  • 142
  • 2
  • 13
  • What have you tried? What output do you expect? It's hard to tell from the question which bit you're struggling with – tim_yates Aug 22 '16 at 09:08
  • I want to find the list of nodes (`groovy.util.slurpersupport.GPathResult`) where attribute value like 'Error_'. Then it will be processed by Error engine. – Alex Aug 22 '16 at 09:23

1 Answers1

6

You can just do a depth-first search of the XML tree:

def xmlString = '''<root>
    <item id="Correction">
        <desc value_err="Error_3"></desc>
    </item>
    <item id_err="Error_2">
        <desc />
    </item>
</root>'''

import groovy.xml.*

def xml = new XmlSlurper().parseText(xmlString)

def nodes = xml.'**'.findAll { node ->
    node.attributes().find { it.value.startsWith 'Error_' }
}
tim_yates
  • 167,322
  • 27
  • 342
  • 338