Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying YAML in java while preserving comments

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.

like image 433
dexterousashish Avatar asked Apr 06 '26 19:04

dexterousashish


1 Answers

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.

like image 115
dosenfant Avatar answered Apr 08 '26 17:04

dosenfant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!