Skip to content

Block Style YAML

Mihai edited this page Mar 29, 2020 · 4 revisions

Block-Style YAML

This is the most common form of YAML. Indentation matters, since it dictates where a node starts and where it ends. In principle, child nodes should be indented after parent nodes by 2 spaces.

Building and printing Yaml:

YamlMapping yaml = Yaml.createYamlMappingBuilder()
    .add("architect", "amihaiemil")
    .add(
        "devops",
        Yaml.createYamlSequenceBuilder()
            .add("rultor")
            .add("0pdd")
            .build()
    ).add(
        "developers",
        Yaml.createYamlSequenceBuilder()
            .add("amihaiemil")
            .add("salikjan")
            .add("SherifWally")
            .build()
    ).build();

final String arch = yaml.string("architect");
final YamlSequence devs = yaml.yamlSequence("developers");
for(final YamlNode dev : devs) { //YamlSequence is an Iterable<YamlNode>
    //...
}

toString() methods are overriden to pretty-print the yaml, so the above yaml.toString() will print:

architect: amihaiemil
devops: 
  - rultor
  - 0pdd
developers: 
  - amihaiemil
  - salikjan
  - SherifWally

Of course, if you want to build a simple sequence, just start with Yaml.createYamlSequenceBuilder().

Reading

Reading all sorts of YAML happens through the Yaml.createYamlInput(...) method. This method is overloaded to accept a String, a File or an InputStream.

Put the above YAML in a file called team.yml and read it:

YamlMapping team = Yaml.createYamlInput(
    new File("team.yml")
).readYamlMapping();
String architect = team.string("architect");
YamlSequence devs = team.yamlSequence("developers");
YamlSequence devops = team.yamlSequence("devops");