如何在Groovy中解析YAML文件? [英] How do I parse a YAML file in groovy?

查看:728
本文介绍了如何在Groovy中解析YAML文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

判断是否有一个名为example.yaml的文件,其中包含以下内容: - subject: maths.

say if you have a file called example.yaml which contains the following: - subject: maths.

我如何在- subject之后抓取字符串?

How do i grab the string after - subject?

我已经可以读取文件的内容,但是想知道如何从文件中获取特定的字符串.

I already can read the contents of the file but want to know how to grab a specific string from it.

注意:我知道正则表达式可能会有所帮助,但从未使用过它,并且希望能获得任何帮助.

note: i know regex may help but have never used it and would appreciate any help.

推荐答案

更新(2020)

Groovy 3现在包含一个groovy.yaml.YamlSlurper(类似于JsonSlurper/XmlSlurper)

Groovy 3 now includes a groovy.yaml.YamlSlurper (similar to JsonSlurper/XmlSlurper)

对于以前的版本(原始答案):

snakeyaml是用于解析YAML文件的库.易于在常规中使用.

snakeyaml is a library to parse YAML files. Easy to use in groovy.

更新:将示例变量的类型更改为列表,因为示例文件的顶级元素是集合

@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}

snakeyaml的完整文档:

Full documentation of snakeyaml:

https://bitbucket.org/asomov/snakeyaml/wiki/Documentation

这篇关于如何在Groovy中解析YAML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆