GB86
GB86

Reputation: 61

How to preserve leading white space while reading yaml

I am reading yaml file with YamlReader(yamlbeans.YamlReader)

- tag: xyz
  description: |  
    This is multi-line comment and I want to preserve  
    leading white spaces and new line  

When I reads the above as given below:

String descr = tag.get("description");  

It gives below output:

This is multi-line comment and I want to preserve  
leading white spaces and new line  

But I want to preserve leading white space.

Upvotes: 6

Views: 4627

Answers (1)

flyx
flyx

Reputation: 39708

Use an indentation indicator:

- tag: xyz
  description: |1
     This is a multi-line comment and I want to preserve
     leading white spaces and new line

The 1 states that the following block scalar will have one space of additional indentation (in addition to the current indentation level) This will give:

  This is a multi-line comment and I want to preserve
  leading white spaces and new line

As you see, the two spaces present after the one indentation space in the block scalar are preserved. You can use any one-digit number as indentation indicator.

If you want to preserve trailing newline characters, use |1+, where + tells YAML to preserve trailing newline characters.

Upvotes: 10

Related Questions