Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy XmlSlurper: Find elements in XML structure

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.

like image 258
Robert Strauch Avatar asked Nov 30 '11 09:11

Robert Strauch


People also ask

What is groovy XmlSlurper?

Groovy's internal XmlParser and XmlSlurper provide access to XML documents in a Groovy-friendly way that supports GPath expressions for working on the document. XmlParser provides an in-memory representation for in-place manipulation of nodes, whereas XmlSlurper is able to work in a more streamlike fashion.

What is GPathResult?

GPathResult, which is a wrapper class for Node. GPathResult provides simplified definitions of methods such as: equals() and toString() by wrapping Node#text().

What is node in groovy script?

Represents an arbitrary tree node which can be used for structured metadata or any arbitrary XML-like tree. A node can have a name, a value and an optional Map of attributes.


1 Answers

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()
like image 64
socha23 Avatar answered Sep 27 '22 20:09

socha23