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 #1
in the <DataFieldName>
element. If found then get the value of the corresponding <DataFieldValue>
which belongs to the same level.
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.
GPathResult, which is a wrapper class for Node. GPathResult provides simplified definitions of methods such as: equals() and toString() by wrapping Node#text().
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With