Groovy XmlSlurper: Find elements in XML structure

23,323

If DataFieldName is unique in a file:

println new XmlSlurper()
    .parseText(xml)
    .DataFieldText.find {it.DataFieldName == "Field #1"}
    .DataFieldValue.text()

If it is not, and you want to get an array with all matching DataFieldValues:

println new XmlSlurper()
    .parseText(xml)
    .DataFieldText.findAll {it.DataFieldName == "Field #1"}*.DataFieldValue*.text()
Share:
23,323
Robert Strauch
Author by

Robert Strauch

Updated on July 05, 2022

Comments

  • Robert Strauch
    Robert Strauch almost 2 years

    Let's say there is the following XML structure:

    <Data>
        <DataFieldText>
            <DataFieldName>Field #1</DataFieldName>
            <DataFieldValue>1</DataFieldValue>
        </DataFieldText>
        <DataFieldText>
            <DataFieldName>Field #2</DataFieldName>
            <DataFieldValue>2</DataFieldValue>
        </DataFieldText>
        <DataFieldText>
            <DataFieldName>Field #3</DataFieldName>
            <DataFieldValue>3</DataFieldValue>
        </DataFieldText>
    </Data>
    

    Using Groovy's XmlSlurper I need to do the following:

    Beginning from Data find that element which contains the value Field #1in the <DataFieldName> element. If found then get the value of the corresponding <DataFieldValue> which belongs to the same level.

  • Dónal
    Dónal over 12 years
    very impressive, after reading this I feel compelled to go and refactor all my XmlSlurper code (curse you)
  • tim_yates
    tim_yates over 12 years
    Isn't that a List of NodeChildren? Better might be: new XmlSlurper().parseText( xml ).DataFieldText.findAll { it.DataFieldName.text() == 'Field #1' }*.DataFieldValue*.text()
  • buczek
    buczek over 7 years
    Welcome to Stackoverflow. When you provide an answer, please include some text about why your answer works and how it differs from the solution answered before.