如何使用snakeyaml

问题描述

我想使用蛇YAML自动化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

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

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文件而不会影响锚和别名。

解决方法

您可以通过遍历事件流而不是构造本机值来做到这一点:

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规范中的以下图表:

您可以插入其他事件以添加内容。 This answer展示了如何在PyYAML中进行操作;由于SnakeYAML的API非常相似,因此用Java重写它应该没有问题。您还可以将所需的其他值写为YAML,将其加载为另一个事件流,然后将该流的内容事件转储到主流中。