groovy 加载 YAML 文件修改并写入文件 [英] groovy load YAML file modify and write it in a file

查看:42
本文介绍了groovy 加载 YAML 文件修改并写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 YMAL 文件,我想使用 groovy 读取和修改一个元素值,然后将其写入另一个文件.

I have YMAL files, using groovy I want to read and modify one element value, then write it into another file.

使用此代码,尝试将第一个文件值从 TopClass.py 修改为 changeclass.py.但它不会修改值.

Playing with this code, trying to modify first filevalue from TopClass.py to changeclass.py. But its not modifying the value.

import org.yaml.snakeyaml.Yaml

class Test{
    def static main(args){
        Yaml yaml = new Yaml()
        def Map  map = (Map) yaml.load(data)
        println map.Stack.file[0]
        map.Stack.file[0]='changeclass.py'
        println map.Stack.file[0]
    }

def static String data="""
Date: 2001-11-23 15:03:17 -5
User: ed
Fatal:
  Unknown variable "bar"
Stack:
  - file: TopClass.py
    line: 23
    code: |
      x = MoreObject("345\n")
  - file: MoreClass.py
    line: 58
    code: |-
      foo = bar
"""

是否有示例 groovy 代码来读取 YAML 文件并修改并将其写入文件?

Is there sample groovy code to read the YAML file and modify and write it into file?

谢谢SR

推荐答案

你的代码的问题是你试图访问一个 Map.Entry 对象 'file' 作为列表.这里 yaml 数据中的 'Stack' 元素是一个包含两个 Map 的列表.所以修改值的正确方法是:

The problem with your code is that you are trying to access a Map.Entry object 'file' as a List. Here the 'Stack' element in your yaml data is a list that contains two Maps. So the correct way to modify the value would be:

map.Stack[0].file = 'changeclass.py'

要将更改数据保存回文件,请使用 dump() 方法.例如:

To save the changes data back to a file, use dump() method. for eg:

DumperOptions options = new DumperOptions()
options.setPrettyFlow(true)
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK)
yaml = new Yaml(options)
yaml.dump(map, new FileWriter(<filePath>))

在您的情况下,输出将是:

Output in your case would be:

Date: 2001-11-23T20:03:17Z
User: ed
Fatal: Unknown variable "bar"
Stack:
- file: changeclass.py
  line: 23
  code: |
    x = MoreObject("345
")
- file: MoreClass.py
  line: 58
  code: foo = bar

这篇关于groovy 加载 YAML 文件修改并写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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