Searching XML element in whole document with Groovy XmlParser

I'm using the Groovy XmlParser to read some XML document. This works fine as long as I know where the elements are located in the tree. However I haven't yet found a way to search the whole XML document for an element like e.g. in XPath //ElementName.

What's the Groovy way of doing this?

Answers


Looking for something like this?

def xml = 
'''
<root>
    <parent>
        <child>
            <firstName>John</firstName>
            <lastName>Doe</lastName>
        </child>
        <child>
            <firstName>Tony</firstName>
            <lastName>Stark</lastName>
        </child>
        <child>
            <firstName>Captain</firstName>
            <lastName>America</lastName>
        </child>
    </parent>
</root>
'''

def parsed = new XmlParser().parseText(xml)
assert ['John', 'Tony', 'Captain'] == 
          parsed.depthFirst().findAll { it.name() == 'firstName' }*.text()

also (as mentioned by Tim) you can use '**' for depthFirst search

assert ['John', 'Tony', 'Captain'] == 
          parsed.'**'.findAll { it.name() == 'firstName' }*.text()

Need Your Help

Handle special characters in mysql search e.g. Sigur Rós

php mysql regex database

My database features names with special characters e.g. Sigur Rós

jqPlot target that doesn't have a static id

javascript jquery charts jqplot

I'm just playing with jqplot for a few hours but I couldn't find how to specify the target in a more specific jquery way.