问题
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