How to auto edit Yaml file containing Anchors & Aliases using snakeyaml

孤人 提交于 2021-01-28 11:44:10

问题


I want to automate YAML file processing using snake YAML

Input:

_Function: &_Template
  Name: A
  Address: B

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

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

After Modifying the desired output is

_Function: &_Template
  Name: A
  Address: B

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

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

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);

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


回答1:


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());

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:

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.



来源:https://stackoverflow.com/questions/63823021/how-to-auto-edit-yaml-file-containing-anchors-aliases-using-snakeyaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!