12

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.

Pieter VDE
  • 2,195
  • 4
  • 25
  • 44
Robert Strauch
  • 12,055
  • 24
  • 120
  • 192

2 Answers2

20

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()
socha23
  • 10,171
  • 2
  • 28
  • 25
  • 1
    very impressive, after reading this I feel compelled to go and refactor all my XmlSlurper code (curse you) – Dónal Nov 30 '11 at 10:11
  • 3
    Isn't that a `List` of `NodeChildren`? Better might be: `new XmlSlurper().parseText( xml ).DataFieldText.findAll { it.DataFieldName.text() == 'Field #1' }*.DataFieldValue*.text()` – tim_yates Nov 30 '11 at 10:21
1
def xml = """<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>"""      
def payload = new XmlSlurper().parseText(xml)     
def node = payload.'**'.find() { myNode -> myNode.DataFieldName.text() == 'Field #1' }     
value = node.DataFieldValue?.text()    
println "${value}\n"    
Brian
  • 31
  • 2
  • 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. – buczek Dec 07 '16 at 16:59