如何自动编辑包含 Anchors & 的 Yaml 文件使用snakeyaml的别名 [英] How to auto edit Yaml file containing Anchors & Aliases using snakeyaml

查看:36
本文介绍了如何自动编辑包含 Anchors & 的 Yaml 文件使用snakeyaml的别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用蛇 YAML 自动处理 YAML 文件

I want to automate YAML file processing using snake YAML

输入:

_Function: &_Template
  Name: A
  Address: B

_Service: &_Service
  Problem1:
   <<: *_Template
  Problem2:
   <<: *_Template

Function.Service:
 Service1:
  <<: *_Service
 Service2:
  <<: *_Service

修改后需要的输出是

_Function: &_Template
  Name: A
  Address: B

_Service: &_Service
  Problem1:
   <<: *_Template
  Problem2:
   <<: *_Template

Function.Service:
 Service1:
  <<: *_Service
 Service2:
  <<: *_Service
 Service2:
  <<: *_Service

是否可以在不干扰 Anchors & 的情况下修改文件?别名,我尝试读取 Yaml 文件并将其写入不同的文件,输出文件包含表单键值对中的 Map 对象.但是如何使用锚点编写输出文件&别名

Is it possible to modify file with out disturbing Anchors & aliases, I tried to read Yaml file and write it into different file, the output file contains Map objects in form key value pairs. But how to write output file with anchors & Aliases

Yaml yaml = new Yaml();
Map<String, Object> tempList = (Map<String, Object>)yaml.load(new FileInputStream(new File("/Users/Lakshmi/Downloads/test_input.yml")));
Yaml yamlwrite = new Yaml();
FileWriter writer = new FileWriter("/Users/Lakshmi/Downloads/test_output.yml");
yamlwrite.dump(tempList, writer);

如果不是snakeYaml,是否有任何语言可以在不干扰锚点的情况下自动修改yaml文件?别名.

If not snakeYaml, is there any language where-in we can auto modify yaml files without disturbing anchors & aliases.

推荐答案

你可以通过迭代事件流而不是构造一个原生值来做到这一点:

You can do this by iterating over the event stream instead of constructing a native value:

final Yaml yaml = new Yaml();
final Iterator<Event> events = yaml.parse(new StreamReader(new UnicodeReader(
        new FileInputStream(new File("test.yml"))).iterator();

final DumperOptions yamlOptions = new DumperOptions();
final Emitter emitter = new Emitter(new PrintWriter(System.out), yamlOptions);
while (events.hasNext()) emitter.emit(events.next());

事件流是对 YAML 文件结构的遍历,其中锚点 &别名尚未解析,请参阅 YAML 规范中的此图:

The event stream is a traversal of the YAML file's structure where anchors & aliases are not resolved yet, see this diagram from the YAML spec:

您可以插入其他事件来添加内容.这个答案展示了如何在 PyYAML 中做到这一点;由于SnakeYAML的API非常相似,所以用Java重写应该没有问题.您还可以将所需的附加值编写为 YAML,将其作为另一个事件流加载,然后将该流的内容事件转储到主流中.

You can insert additional events to add content. This answer shows how to do it in PyYAML; since SnakeYAML's API is quite similar, it should be no problem to rewrite this in Java. You can also write the desired additional values as YAML, load that as another event stream and then dump the content events of that stream into the main stream.

这篇关于如何自动编辑包含 Anchors &amp; 的 Yaml 文件使用snakeyaml的别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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