How can we modify an existing YAML and preserve comments in it. Is there any Java parser which does that ? For example if i have following YAML:
#This is a test YAML
name: abcd
age: 23
#Test YAML ends here.
Is there a way I can edit this Yaml using a java parser and preserve the comments.
At least since snakeyaml 2.0 (which I'm using) it is possible to preserve comments. The only drawback seems to be that you cannot parse the YAML to a Map or some other class, because that erases the comment information. That is only stored in snakeyaml's internal Nodes.
LoaderOptions loaderOptions = new LoaderOptions();
loaderOptions.setProcessComments(true);
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setProcessComments(true);
Yaml yaml = new Yaml(new Constructor(loaderOptions), new Representer(dumperOptions), dumperOptions, loaderOptions);
Node root;
try (FileReader reader = new FileReader(yamlFile)) {
root = yaml.compose(reader);
}
try (FileWriter writer = new FileWriter(cloneFile)) {
yaml.serialize(root, writer);
}
The only difference I get between in- and output are different line endings (can be configured in the DumperOptions) and some of my previously empty lines will have indenting spaces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With