I am adding here the same example, but implemented with the native YAMLSlurper
(Groovy 3.x+):
import groovy.yaml.YamlSlurper
def exampleYaml = '''\
---
- subject: "maths"
- subject: "chemistry"
'''
List example = new YamlSlurper().parseText(exampleYaml)
// If your source is a File
// List example = new YamlSlurper().parse("example.yaml" as File)
example.each{println it.subject}
For previous versions (Original answer):
snakeyaml
is a library to parse YAML files. Easy to use in groovy.
UPDATE: changed type of the example variable to List, as the example file's top level element is a collection
@Grab('org.yaml:snakeyaml:1.17')
import org.yaml.snakeyaml.Yaml
Yaml parser = new Yaml()
List example = parser.load(("example.yaml" as File).text)
example.each{println it.subject}
Full documentation of snakeyaml
:
https://bitbucket.org/snakeyaml/snakeyaml/wiki/Documentation